I have the following regular XML
file:
<root>
<Items>
<Item>
<tag1>text1</tag1>
<tag2>text2</tag2>
<tag3>text3</tag3>
</Item>
<Item>
<tag1>text1</tag1>
<tag2>text4</tag2>
<tag3>text5</tag3>
</Item>
</Items>
</root>
And I want to get all nodes (all <Item>
) where <tag1>
text equals to text1
, and then print their all other tags for example <tag2>
.
I started with this but struggling to find answers to the TODO'S:
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(("\URI\file.xml"));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
//TODO: Is this correct query?
XPathExpression expr = xpath.compile("//root//Items//Item//tag1[contains(., 'text1')]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i=0; i<nl.getLength(); i++) {
//TODO: How to iterate over all matched <Item> and get their <tag2>, <tag3> etc.?
}
} catch (Exception e) {e.printStackTrace();}
Thanks,