In Java, how to evaluate XPATH expression on XML using SAX Parser?


In Java how do I evaluate XPATH expression on XML using SAX Parser?

Need more dynamic way because the XML format is not fixed. So i should be able pass the following

  1. xpath as string
  2. xml as string / input source

Something like Utility.evaluate("/test/@id='123'", "")

Here is an exemple :

//First create a Document
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("test.xml"));

//Init the xpath factory
XPath xPath =  XPathFactory.newInstance().newXPath();
String expression = "/company/employee";

//read a nodelist using xpath
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);


If you want to use a SAX parser, then you can't use the XPath object of Java, see

The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value. XPath is a W3C-defined language and an official W3C recommendation; the W3C hosts the XML Path Language (XPath) Version 1.0 specification.

XPath started in life in 1999 as a supplement to the XSLT and XPointer languages, but has more recently become popular as a stand-alone language, as a single XPath expression can be used to replace many lines of DOM API code.

If you want to use SAX you can look at libs detailed in this question : Is there any XPath processor for SAX model? .

Although the mechanic of XPath does not really suit SAX. Indeed using a SAX parser won't create an XML tree in memory. Hence you can't use XPath efficiently because it won't see not loaded nodes.