Gobliins
Gobliins

Reputation: 4026

Howto iterate through XML by node/element names

Is there a way i can iterate over nodes/elements by their names like this:

<rootnode>
  <foo>
    <bar>
      stuff
    </bar>
 ....


document.getDocumentElement.getElement("foo").getElement("bar").getValue();

Upvotes: 0

Views: 80

Answers (1)

Yuriy Privezentsev
Yuriy Privezentsev

Reputation: 66

I think the XPath should do the trick.

Provided you already have parsed the document as org.w3c.dom.Document:

String expression = "/rootnode/foo/bar";
NodeList nodeList = (NodeList)   xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}

Upvotes: 2

Related Questions