我从谷歌了解到,使用XPath从XML中提取数据比使用DOM循环更有意义.
目前,我已经使用DOM实现了一个解决方案,但是代码很冗长,感觉不整洁且不可维护,所以我想切换到更清洁的XPath解决方案.
假设我有这样的结构:
Some title 1Some image 1
Some title 2Some image 2
...
我希望能够为每个< 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>作为一个节点,它被转换为一个元素.
我可以简单地使用我的XPathExpression实例来编译和运行Node或Element上的另一个XPath吗?