【发布时间】:2012-07-25 13:21:24
【问题描述】:
我想使用 xPath 检查我的 xml 文件中是否存在 code = "ABC" 。您能建议我一些方法吗?
<metadata>
<codes class = "class1">
<code code = "ABC">
<detail "blah blah"/>
</code>
</codes>
<codes class = "class2">
<code code = "123">
<detail "blah blah"/>
</code>
</codes>
</metadata>
[编辑] 我做了以下。它返回 null。
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//codes/code[@ code ='ABC']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("nodes: "+ nodes.item(i).getNodeValue());
}
【问题讨论】:
-
你试过什么?你搜索过什么?你的障碍到底在哪里?
-
这不是有效的 xml,
<code="ABC">缺少属性名称 -
你的匹配模式“@code =”中真的有空格吗?如果是这样,请删除那些额外的空格。此外,元素的“nodeValue”为“null”,因此您的代码实际上可能正在工作。你应该打印出更有意义的东西。