thunderbird
thunderbird

Reputation: 2733

xpath not working in java

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.

Upvotes: 3

Views: 2272

Answers (2)

Michael Kay
Michael Kay

Reputation: 163585

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

Upvotes: 2

Gottfried Lesigang
Gottfried Lesigang

Reputation: 67321

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...

Upvotes: 1

Related Questions