tags:

views:

56

answers:

2

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.

+1  A: 

Have you seen The Java XPath API.

Hank Gay
+2  A: 

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());
        }
    }

}
toolkit