Java XPath List Retrieval Guide

In Java, the method to retrieve a list using XPath is to select elements using XPath expressions and store them in a NodeList object. Here is a simple example code:

import javax.xml.xpath.*;
import org.w3c.dom.*;

public class XPathExample {

    public static void main(String[] args) {
        try {
            // 创建 XPath 对象
            XPath xPath = XPathFactory.newInstance().newXPath();

            // 编译 XPath 表达式
            XPathExpression expression = xPath.compile("//book");

            // 获取 XML 文档
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse("books.xml");

            // 在文档上应用 XPath 表达式
            NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

            // 遍历 NodeList
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                System.out.println(node.getNodeName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In the example above, we used the XPath expression //book to select all book elements in the document and stored them in a NodeList object. We then iterated through the NodeList and outputted the node name of each element. Note that you will need to replace the XML document path and XPath expression in the example code to fit your own needs.

bannerAds