HitchHiker
HitchHiker

Reputation: 847

Extracting the node values in XML with XPath in Java

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!

Upvotes: 1

Views: 1407

Answers (1)

Adam
Adam

Reputation: 36743

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

Upvotes: 1

Related Questions