Android - 如何在xml中的标签之间提取数据

时间:2012-04-28 04:56:56

标签: android xml eclipse

我有一个res / xml / myxmlfile看起来像这样(抱歉屏幕截图,我不确定如何在stackoverflow编辑器中正确显示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>

我想编写一个函数,将食物类型作为参数(例如Burger),并将标记之间的所有项目加载到字符串[i]中。

所以函数会是这样的:

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; 
}

如何从main调用该函数的示例:

string[] subFoodType;

subFoodType = GetAllSubFoodTypes("Burger")

subFoodType的内容将是:

subFoodType[0]将是“鸡”,subFoodType[1]将是“培根”等等。

2 个答案:

答案 0 :(得分:0)

您可以使用xml解析,如pull解析器,DOM解析器和SAX解析器

答案 1 :(得分: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());