我从Google Googling了解到,使用XPath从XML中提取数据比使用DOM循环更有意义。使用Java的XPath循环遍历节点并提取特定的子节点值
目前,我已经实现了一个使用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循环,提取标题和图像节点值。
我的代码如下所示:
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
?