Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath not working in java

Tags:

java

xml

xpath

I have the below xml string

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Structure>
   <LongUnsigned value="142794"/>
   <OctetString value="07E2051E030F1E0404800000"/>
   <Structure>
      <OctetString value="07E2051E030F1E0404800000"/>
      <OctetString value="66574536387"/>
      <Array>
         <Structure><OctetString value="0000000000000001"/><OctetString value="9889892347"/></Structure>
         <Structure><OctetString value="00098347586768574"/><OctetString value="6283046502"/></Structure>
         <Structure><OctetString value="0000011000000001"/><OctetString value="899734729847586"/></Structure>
      </Array>
   </Structure>
</Structure>

I am using the below xpath but it always returns an empty string.

        XPath xPath = XPathFactory.newInstance().newXPath();
        try {
            String eval = xPath.evaluate("//Structure/Structure/Array", new InputSource(new StringReader(xmlString)));
            System.out.println("Eval:" + eval);
        } catch (XPathExpressionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

I tried running this xpath online and it seems to work just fine. What am i missing in Java that makes it not work as expected.

like image 440
thunderbird Avatar asked Mar 24 '26 02:03

thunderbird


2 Answers

Your XPath expression selects an element node, not a string. So you need to ask for the result to be returned as a NODESET.

like image 148
Michael Kay Avatar answered Mar 25 '26 17:03

Michael Kay


I'm not familiar with Java reading XML but your XPath should be something like this:

/Structure/Structure/Array/Stucture/OctetString/@value

This will start at the root-node <Structure>, move down to the nested <Structure>, further down to <Array>, then to the nested <OctetString> elements to fetch their value attribute.

Your expression //Structure/Structure/Array starts at any <Structure> (due to the //) and tries to read the value of <Array>, but there is no value, just deeper nodes...

like image 38
Shnugo Avatar answered Mar 25 '26 16:03

Shnugo



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!