3

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.

3
  • 1
    Shouldn't the context be a Document node? Are you sure it is correct to use an InputSource as the context? Commented Jun 4, 2018 at 0:38
  • 2
    Your xml doesn’t contain any text data. You need to call the 3-argument version of evaluate and pass XPathConstants.NODESET or XPathConstants.NODE as the last argument. Commented Jun 4, 2018 at 0:47
  • @JimGarrison it could be either. I tried with both Document and InputSource as a string. The string was actually generated from a Document instance. Commented Jun 4, 2018 at 9:11

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

an upvote for you. The other answer by Michael Kay was exactly what i intended to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.