2012-04-28 55 views
0

我有一個res/xml/myxmlfile看起來像這樣(對於屏幕截圖抱歉,我不確定如何在stackoverflow編輯器中正確顯示xml文件):Android如何提取XML中的標籤之間的數據

<Food> 
    <Pizza> 
     <type>Salami</type> 
     <type>Pepperoni</type> 
     <type>Hawaiian</type> 
    </Pizza> 
    <Burger> 
     <type>Chicken</type> 
     <type>Bacon</type> 
     <type>Cheese</type> 
    </Burger> 
    <Soup> 
     <type>Pumpkin</type> 
     <type>Sweet Corn</type> 
     <type>Vegetarian</type> 
    </Soup> 
</Food> 

我想編寫一個函數,食物的類型作爲參數(例如漢堡),並加載所有標籤之間的物品轉換成字符串[1]。

所以功能會是這樣的:你想怎麼稱呼從主功能

public string[] GetAllSubFoodTypes (string foodtype) 
{ 
    string[] contents; 

    //--- pseudocode as I don't know how to do this 
    Loadxmlfile 
    Find the <foodtype> tag in file 
    Load all data between <type> and </type> into the string[] contents 
    return contents; 
} 

例如:然後

string[] subFoodType; 

subFoodType = GetAllSubFoodTypes("Burger") 

subFoodType的內容將是:

subFoodType[0]將「雞肉」,subFoodType[1]將「培根」等。

+0

用戶xml解析 – Aerrow 2012-04-28 05:08:24

回答

0

你可以使用DOM API,例如:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
Document document = builder.parse("input.xml"); 

XPath xpath = XPathFactory.newInstance().newXPath(); 
String expression = "/Food/Pizza/type[1]"; // first type 
Node pizza = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); 

if (pizza== null) 
    System.out.println("Element pizza type not exists"); 
else 
    System.out.println(pizza.getTextContent()); 
0

您可以使用XML解析像拉解析器,DOM解析器和SAX解析器