Java HTML / XML How to - Select all nodes in document with specified name in XPath








Question

We would like to know how to select all nodes in document with specified name in XPath.

Answer

import java.io.File;
//  w  w w. java 2  s. c  o  m
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        .parse(new File("Test.xml"));
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression exp = xPath.compile("//data");
    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    System.out.println("Found " + nl.getLength() + " results");
  }

}