Java evaluate xpath on xml string

In Java, you can use the Document Object Model (DOM) API to create a DOM tree from an XML string, and then use the XPath API to evaluate XPath expressions on the DOM tree.

Here's an example of how to evaluate an XPath expression on an XML string in Java:

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;

public class XPathExample {
  public static void main(String[] args) throws Exception {
    String xml = "<books><book><title>Cryptonomicon</title><author>Neal Stephenson</author></book><book><title>The Diamond Age</title><author>Neal Stephenson</author></book></books>";
    
    // Create a DOM builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    InputSource is = new InputSource(new StringReader(xml));
    Document doc = factory.newDocumentBuilder().parse(is);

    // Create an XPath object
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    
    // Compile the XPath expression
    XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");
    
    // Evaluate the XPath expression against the DOM tree
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    
    // Process the result
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
      System.out.println(nodes.item(i).getNodeValue());
    }
  }
}
S‮o‬urce:www.theitroad.com

In this example, we first create a DOM tree from an XML string using a DocumentBuilder object. We set the namespaceAware flag to true to enable processing of XML namespaces.

We then create an XPath object and compile an XPath expression. The XPath expression in this example selects the titles of all books whose author is "Neal Stephenson".

We then evaluate the XPath expression against the DOM tree using the evaluate() method of the XPath object. The second argument to the evaluate() method specifies the type of result we expect. In this example, we expect a NODESET result, which is a list of nodes that match the XPath expression.

Finally, we process the result by iterating over the list of nodes and printing their values.

Note that this example uses the javax.xml.xpath package, which is available in Java 5 and later. If you are using an earlier version of Java, you will need to use a third-party XPath library such as Jaxen or Xalan-J.