0

I have a res/xml/myxmlfile which looks something like this (sorry for the screenshot, I am unsure how to display the xml file properly in the stackoverflow editor):

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

I want to write a function that takes the type of food as a parameter (e.g. Burger) and loads all the items between the tags into a string[i].

So function would be something like this:

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

Example of how you'd call the function from main:

string[] subFoodType;

subFoodType = GetAllSubFoodTypes("Burger")

Contents of subFoodType will then be:

subFoodType[0] will be "Chicken", subFoodType[1] will be "Bacon" and so on.

4

2 回答 2

0

您可以使用 xml 解析,例如 pull parser、DOM parser 和 SAX parser

于 2012-04-28T06:20:39.833 回答
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());
于 2012-04-28T06:34:24.223 回答