我从谷歌上了解到,使用 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
实例吗?编译并运行另一个 XPath
在 Node
上或 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/