Thursday, March 24, 2011

XPath in Java

XPath is support in Java by default. In other to use is, you need to parse XML document using DOM (or maybe SAX -- I don't know if that works). Either way, when you do that, just call XPathFactory.newInstance().newXPath() and call evaluate method, like in following example:

public static Object xPathQuery(String expression, File file) {
         Document document;
         DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
         Object result = null;
         try {
             DocumentBuilder builder = dBF.newDocumentBuilder();
             document = builder.parse(file);
             XPath xpath = XPathFactory.newInstance().newXPath();
             XPathExpression expr = xpath.compile(expression);

             result = expr.evaluate(document, XPathConstants.NODESET);             
         } catch (Exception e) {
         return result;

You can see that this method returns Object. This object can be cast to boolean, String or (more useful) NodeList. Be careful, this type depends of type of your XPath query. So for example to extract NodeList from XPath query that returns multiple nodes will look like this:

NodeList nodes = (NodeList) xPathQuery("//employees", new File("C:/some_xml"));

int j = nodes.getLength();

for (int i = 0; i < j; i++) {

And that's it!

No comments:

Post a Comment