Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XPath get all nodes with specific tag matching specific text

Tags:

java

xml

xpath

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,

like image 391
michael Avatar asked May 11 '26 11:05

michael


1 Answers

You can use Chrome Developer Tools $x("path") function for testing XPaths. It's really easy. It works on latest Firefox too.

I made an HTML file with your supplied text and opened it in Chrome. In console, type $x("/some-path") to test stuff.

  1. Get items:

    //Item
    
  2. Where tag1 text equals text1:

    //Item/tag1[.='text1']
    
  3. Get following sibling that is a tag2:

    //Item/tag1[.='text1']/following-sibling::tag2
    

If you want the Item and not the tag2:

//Item[ ./tag1[.='text1']/following-sibling::tag2 ]
like image 179
Neil McGuigan Avatar answered May 14 '26 03:05

Neil McGuigan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!