【问题标题】:java xpath should show subnodes only without attributes, but shows alljava xpath 应该只显示没有属性的子节点,但显示所有
【发布时间】: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文件?

谢谢。

【问题讨论】:

    标签: java xml xpath


    【解决方案1】:

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

    【讨论】:

    • 谢谢,但这似乎行不通。所以表达式现在是: "/testCars/cars[not(@*)]/color[@id=\"0\"]" 但是在评估表达式后没有找到节点。两个版本,也特别排除 id 找不到节点。
    • 如果我删除颜色部分,它确实会找到一个没有属性的节点......
    • 我的错,最后一个的颜色 id 中有多余的 ">"。
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多