XPath Evaluates Compiled Expressions

Evaluate XPath expressions against a DOM document: compile once for reuse, read scalars as strings, counts as NUMBER, node sets as NODESET.

JavaData Fetching

Code

snippet
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
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 XPathEvaluateExpressions {

    public static void main(String[] args) throws Exception {
        String xml = """
                <inventory>
                    <item sku="A-1" stock="5">keyboard</item>
                    <item sku="B-2" stock="0">mouse</item>
                    <item sku="C-3" stock="9">monitor</item>
                </inventory>""";

        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));

        XPath xpath = XPathFactory.newInstance().newXPath();

        // compile 先编译表达式,可对多个上下文复用
        XPathExpression inStock = xpath.compile("count(//item[@stock > 0])");
        System.out.println("in stock items = "
                + ((Double) inStock.evaluate(document, XPathConstants.NUMBER)).intValue());

        // 直接 evaluate:标量默认返回 String
        System.out.println("first item = " + xpath.evaluate("/inventory/item[1]", document));

        // NODESET 返回 NodeList,逐个取属性值
        NodeList outOfStock = (NodeList) xpath.evaluate(
                "//item[@stock = '0']/@sku", document, XPathConstants.NODESET);
        for (int i = 0; i < outOfStock.getLength(); i++) {
            System.out.println("out of stock sku = " + outOfStock.item(i).getNodeValue());
        }
    }
}

What the code does

XPath Evaluates Compiled Expressions keeps everything in the class XPathEvaluateExpressions.

Iteration happens inside for (int i = 0; i < outOfStock.getLength(); i++) — everything outside it runs once.

Points of care

  • Dependency check: org.w3c.dom.Document and org.w3c.dom.NodeList — not built-in, must be present in the project.

Applying it

The demo output is labeled (in stock items =, first item =, out of stock sku =); each label names the call that printed it.

Statements that matter

.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
XPathExpression inStock = xpath.compile("count(//item[@stock > 0])");
XPath xpath = XPathFactory.newInstance().newXPath();

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `org.w3c.dom.Document` and `org.w3c.dom.NodeList`. Without them the snippet will not load.