java - 使用 Java 的 XPath 遍历节点并提取特定的子节点值

标签 java xpath

我从谷歌上了解到,使用 XPath 从 XML 中提取数据比使用 DOM 循环更有意义。

目前,我已经实现了一个使用 DOM 的解决方案,但代码冗长,感觉不整洁且难以维护,所以我想切换到更干净的 XPath 解决方案。

假设我有这个结构:

<products>
    <product>
        <title>Some title 1</title>
        <image>Some image 1</image>
    </product>
    <product>
        <title>Some title 2</title>
        <image>Some image 2</image>
    </product>
    ...
</products>

我希望能够为每个 <product> 运行一个 for 循环元素,并在此 for 循环内,提取标题和图像节点值。

我的代码是这样的:

InputStream is = conn.getInputStream();          
DocumentBuilder builder =
  DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("/products/product");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList products = (NodeList) result;
for (int i = 0; i < products.getLength(); i++) {
    Node n = products.item(i);
    if (n != null && n.getNodeType() == Node.ELEMENT_NODE) {
        Element product = (Element) n;
        // do some DOM navigation to get the title and image
    }
}

在我的 for 里面循环我得到每个 <product>作为Node , 它被转换为 Element .

我可以简单地使用我的 XPathExpression 实例吗?编译并运行另一个 XPathNode 上或 Element

最佳答案

是的,你总是可以这样做 -

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("/products/product");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
expr = xpath.compile("title"); // The new xpath expression to find 'title' within 'product'.

NodeList products = (NodeList) result;
for (int i = 0; i < products.getLength(); i++) {
    Node n = products.item(i);
    if (n != null && n.getNodeType() == Node.ELEMENT_NODE) {
        Element product = (Element) n;
        NodeList nodes = (NodeList)  expr.evaluate(product,XPathConstants.NODESET); //Find the 'title' in the 'product'
        System.out.println("TITLE: " + nodes.item(0).getTextContent()); // And here is the title 
    }
}    

这里我给出了提取'title'值的例子。以同样的方式你可以为“图像”做

关于java - 使用 Java 的 XPath 遍历节点并提取特定的子节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3996385/

相关文章:

java - 如何在 HashMap 中保存树结构?

sql - XPath 根据 SQL Server xml 中的属性 'A' 获取属性 'B' 的值

php - 使用 PHP(XPath)、PHP/Python(Regex) 或 Python(XPath) 从 html 中提取信息

Java 谷歌 checkstyle Maven

java - Android:从 Assets 文件夹中读取并格式化文本

java - 是否可以使用 Mockito 模拟静态和无效的方法?

xpath - 处理动态 Xpath

xml - 如何从 XML 中提取子节点值作为字符串

xml - Xpath 不适用于 XML::Twig::XPath::Elt

java - 无法通过使用java执行shell脚本来创建文件夹