【发布时间】:2016-02-05 14:18:58
【问题描述】:
我有以下常规XML 文件:
<root>
<Items>
<Item>
<tag1>text1</tag1>
<tag2>text2</tag2>
<tag3>text3</tag3>
</Item>
<Item>
<tag1>text1</tag1>
<tag2>text4</tag2>
<tag3>text5</tag3>
</Item>
</Items>
</root>
我想获取所有节点(所有<Item>),其中<tag1> 文本等于text1,然后打印它们的所有其他标签,例如<tag2>。
我从这个开始,但努力寻找 TODO'S 的答案:
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(("\URI\file.xml"));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
//TODO: Is this correct query?
XPathExpression expr = xpath.compile("//root//Items//Item//tag1[contains(., 'text1')]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i=0; i<nl.getLength(); i++) {
//TODO: How to iterate over all matched <Item> and get their <tag2>, <tag3> etc.?
}
} catch (Exception e) {e.printStackTrace();}
谢谢,
【问题讨论】: