首页javaxpathJava HTML/XML - 如何在Java XPath查询中使用name()和/或node()

Java HTML/XML - 如何在Java XPath查询中使用name()和/或node()

我们想知道如何在Java XPath查询中使用name()和/或node()。
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());
    }
  }
}