XPath Evaluation in Java : Xalan XPath API vs Apache XmlBean

1 minute read

How to evaluate Xpath value for an XML in Java?

Well there are couple of popular ways to evaluate XPath in Java. If you are using JDK 1.4 version than Xalan’s XPathAPI class is one of the most popular ways to evaluate XPath. Using XPathAPI is simple, use the following static method from XPathAPI class:

XPathAPI.selectNodeList(Document d,  String XPath)

which returns a NodelList.

Another way of XPath evaluation is using Apache XmlBean project. Though Apache XmlBean is used for XML Binding, it can safely be used for XPath evaluation as well.  A simple exmaple of evaluating XPath using XmlBean is as below:

</p>

XmlObject obj = XmlObject.Factory.parse(InputStream);
XmlObject x[] = obj.selectPath(xPath);

Another example of using XmlBean to evaluate XPath using cursor is :

XmlObject obj = XmlObject.Factory.parse(InputStream);
XmlCursor xcur = obj.newCursor();
xcur.toFirstChild();
xcur.selectPath(
xPath); 
if(xcur.hasNextSelection()){
            xcur.toNextSelection();
            String s = xcur.getTextValue();
           System.
out.println(s);
}
xcur.dispose();

 

</span>

XPathAPI vs XmlBean

Well this is not a generic comparison as one of them, XmlBean, definitely does a lot more than evaluating XPath and we have just found a way (probably) of using it to evaluate XPath. This comparison is limited to evaluating XPath.

So which one of the methods should one use if all we want to do is evaluate XPath. I tried to do some performance benchmarking using a simple example with no complexities involed. For 25000 transactions, where each transaction included both parsing and XPath evaluation, the results are:

  • Both APIs take almost the same amount of time in parse() so we can neglect the parse time as it’s not the XPathAPI that is doing the parsing for it. XmlBean parsing however cannot be externalized.
  • The XPath evaluation time: The XPath evaluation time for XmlBean is drastically lower than that of XPathUtil. It varis from being 1/6th to 1/3rd of the time taken by XPathUtil.

The test however took simple XML Paths to evaluate that returns single & multiple nodes.

While considering an API to use for an application, there are many more factors to consider. If you already have XmlBean in your application, use it for XPath evaluation.

Leave a Comment