【发布时间】:2020-02-18 16:47:15
【问题描述】:
我有一个简单的示例 xml 文件:
<?xml version="1.0" ?>
<testCars>
<cars id="0">
<color id="0">Black</color>
<color id="1">Orange</color>
</cars>
<cars id="1">
<color id="0">Blue</color>
<color id="1">Grey</color>
</cars>
<cars>
<color id="0>">Red</color>
<color id="1>">Green</color>
</cars>
</testCars>
首先我使用 DocumentBuilder 来解析该文件,然后我使用 xpath 来获取我想要的东西。 我会使用表达式和 xpath 来获取汽车 1 的颜色 0:
String expression = String.format("/testCars/cars[@id=\"%s\"]/color[@id=\"%s\"]",1,0);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
System.out.println(nodeList.item(0).getTextContent());
我应该得到蓝色。但是假设我想要一张没有 ID 的卡片的颜色 0,它应该是红色。
所以我把表达式改为
String expression = String.format("/testCars/cars/color[@id=\"%s\"]",0);
但现在结果是黑色。它只占用第一个节点,尽管我希望它占用没有任何属性的节点。
Xpath 是否有一些特定的命令来显式选择没有属性的节点?还是需要重构xml文件?
谢谢。
【问题讨论】: