App下載
首頁(yè)javaxpathJava HTML/XML - 如何使用Xpath檢查Xml文件中是否存在特定節(jié)點(diǎn)

Java HTML/XML - 如何使用Xpath檢查Xml文件中是否存在特定節(jié)點(diǎn)

我們想知道如何使用Xpath檢查Xml文件中是否存在特定節(jié)點(diǎn)。
import java.io.ByteArrayInputStream;

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.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {

    String xml = "<metadata><codes class = 'class1'>" + "<code code='ABC'>"
        + "<detail x='blah blah'/>" + "</code>" + "</codes>"
        + "<codes class = 'class2'>" + "<code code = '123'>"
        + "<detail x='blah blah'/></code></codes></metadata>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("http://codes/code[@code ='ABC']");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength() > 0 ? "Yes" : "No");
    for (int i = 0; i < nodes.getLength(); i++) {
      System.out.println("nodes: " + nodes.item(i).getNodeValue());
    }
  }
}