How to read XML using XPath in Java

To read XML using XPath in Java, you can use the javax.xml.xpath package.

Here is an example of how to read an XML file using XPath:


import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {
    // create XPath
    XPath xpath = XPathFactory.newInstance().newXPath();

    // create InputSource
    InputSource inputSource = new InputSource(new File("example.xml").toURI().toString());

    // compile XPath expression
    XPathExpression expression = xpath.compile("/root/element");

    // evaluate XPath expression
    NodeList nodes = (NodeList) expression.evaluate(inputSource, XPathConstants.NODESET);

    // process nodes
    for (int i = 0; i < nodes.getLength(); i++) {
      String value = nodes.item(i).getTextContent();

This example reads an XML file called example.xml and uses XPath to select all element nodes under the `