首页javaxpathJava HTML/XML - 如何从DOM评估XPath

Java HTML/XML - 如何从DOM评估XPath

我们想知道如何从DOM评估XPath。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class Main {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document xml = db.parse("input.xml");

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        String health = (String) xpath.evaluate("/game/health", xml, XPathConstants.STRING);
        System.out.println(health);
    }
}