Java HTML / XML How to - Evaluate XPath from DOM








Question

We would like to know how to evaluate XPath from DOM.

Answer

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;
/* w  w  w  . j ava 2s .com*/
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);
    }
}