user9132502
user9132502

Reputation:

Get all elements inside a specific node

I'm new to XML parsing and I'm lost. First, here's my XML:

<?xml version="1.0" encoding="UTF-8"?>
<menu>
    <data>
        <food type="none">
            <price>100</price>
        </food>
        <food type="none">
            <price>50</price>
        </food>
    </data>

    <trash>
        <food type="none" id="1"/>
        <food type="none" id="2"/>
    </trash>
</menu>

I'm trying to parse this XML. I want to get all food items inside data.

When I do:

NodeList nUsines = doc.getElementsByTagName("food");

I also get the food items in trash, but I don't want this.

And sorry if my questions sounds off, I don't know the proper terms for XML

My code so far (inside a method):

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file.getPath());
    doc.getDocumentElement().normalize();

    NodeList nUsines = doc.getElementsByTagName("food");

Thank you

Upvotes: 0

Views: 345

Answers (2)

Yuriy
Yuriy

Reputation: 1394

Using XPath (just one of the options):

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//data/food");

System.out.println(((NodeList)expr.evaluate(doc, XPathConstants.NODESET)).getLength());

Upvotes: 0

tremby
tremby

Reputation: 10069

Your code has done exactly what you asked it to.

You want a more specific query, such as food elements within the data element.

You could try to select the data element, then query for food elements specifically within that.

Alternatively, look up XPath, and you'll quickly find another way to do this.

Upvotes: 1

Related Questions