javaxpath应该只显示不带属性的子节点,但显示所有子节点



我有一个简单的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文件?

Thx。

要选择没有属性的cars元素,请使用cars[not(@*)]。要选择不具有@id属性的cars元素,请使用cars[not(@id)]

最新更新