2012-04-28 45 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解析器

相关问题