1

I have an XML document:

<response>
    <result>
        <phone>1233</phone>
        <sys_id>asweyu4</sys_id>
        <link>rft45fgd</link>       
            <!-- Many more in result -->
    </result>

    <!-- Many more result nodes -->

</response>

The XML structure is unknown. I am getting XPath for attributes from user.

e.g. inputs are strings like: //response/result/sys_id , //response/result/phone

How can I get these node values for whole XML document by evaluating XPath?

I referred this but my xpath is as shown above i.e it does not have * or text() format.

The xpath evaluator works perfectly fine with my input format, so is there any way I can achieve the same in java?

Thank you!

1 Answer 1

1

It's difficult without seeing your code... I'd just evaluate as a NodeList and then call getTextContent() on each node in the result list...

String input = "<response><result><phone>1233</phone><sys_id>asweyu4</sys_id><link>rft45fgd</link></result><result><phone>1233</phone><sys_id>another-sysid</sys_id><link>another-link</link></result></response>";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        .parse(new ByteArrayInputStream(input.getBytes("UTF-8")));
XPath path = XPathFactory.newInstance().newXPath();
NodeList node = (NodeList) path.compile("//response/result/sys_id").evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < node.getLength(); i++) {
    System.out.println(node.item(i).getTextContent());
}

Output

asweyu4
another-sysid
Sign up to request clarification or add additional context in comments.

2 Comments

this gives only first sys_id, I want all the sys_is field's values
I've updated so it finds "asweyu4" and "another-sysid"... Can you provide an example of your expected output....

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.