Java HTML / XML How to - Use name() and/or node() in Java XPath query








Question

We would like to know how to use name() and/or node() in Java XPath query.

Answer

/* www .  ja va  2s.c o  m*/
import java.io.File;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
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.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    XPath xPath = XPathFactory.newInstance().newXPath();
    FileInputStream file = new FileInputStream(new File("c:/data.xml"));

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory
        .newInstance();

    DocumentBuilder builder = builderFactory.newDocumentBuilder();

    Document xmlDocument = builder.parse(file);

    XPathExpression expr = xPath.compile("//project/*");
    NodeList list = (NodeList) expr.evaluate(xmlDocument,
        XPathConstants.NODESET);
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      System.out.println(node.getNodeName() + "=" + node.getTextContent());
    }
  }
}