0

Total newbie to XPath and Java here. What I'm attempting to do is something like this:

<A>
  <B>
   <C>test 1</C>
  </B>
  <B>
   <C/>test 2</C>
  </B>
  <B>
   <C/>test 3</C>
  </B>
</A>

for each XMLDoc.children() as BNode
  array.append(BNode.getXPathValueAt('B/C'));
end for each

Is there an easy way in Java to use XPaths like that to get deeply nested values in an XML document? I just need a quick and easy way to pull XPath values out of one XML document, and eventually stick them into a hashmap or object.

2 Answers 2

3

Example code. Cheers:

public class XPathExample {

    static final String XML =
        "<A>" +
        "  <B><C>test 1</C></B>" +
        "  <B><C>test 2</C></B>" +
        "  <B><C>test 3</C></B>" +
        "</A>";

    public static void main(final String[] args) throws Exception {
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        final InputSource xml = new InputSource(new StringReader(XML));
        final NodeList list = (NodeList) xpath.evaluate("A/B/C", xml, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            final Node node = list.item(i);
            System.out.println(node.getTextContent());
        }
    }

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

Comments

1

Have you seen The Java XPath API.

Comments

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.