XPath查询如何根据两个属性获取一个属性的值

13

我想从以下标签中提取name属性值

<application
    comments="Do not erase this one"
    executable="run_CIET"
    icon="default"
    instances="1"
    mode="1"
    name="CIET"
    order="10"
    selection="1"
    tool="y"
/>

根据以下示例,我可以轻松地获取基于模式值的name属性值

xpath Applications.xml '//applications/application[@mode='3']'/@name

但是如果我想要添加更多的条件,例如“当mode=X且application标签中不存在tool属性时,获取name属性值”,我们应该怎么做?我尝试过类似以下的代码:

xpath Applications.xml '//applications/application[@mode='3' and !@tool]'/@name

但它没有起作用。

我以前没有使用过XPath,现在发现很棘手。我在W3C的XPath帮助文档中搜索,但没有找到我想要的内容。请帮帮我。


好问题,+1。请看我的答案,其中解释了你的问题,提供了一个简短而完整的解决方案和一些建议。 :) - Dimitre Novatchev
2个回答

18
How do we do this? I tried something like 

    xpath Applications.xml '//applications/application[@mode='3' and !@tool]'/@name

but its not working.



!@tool

在XPath中,! 不是有效的语法,但是存在!= 运算符。

使用方法:

//applications/application[@mode='3' and not(@tool)]/@name 

有两件事情你应该尽量避免:

  1. 使用 != 运算符--它的定义很奇怪,不像 not() 函数那样运行--如果操作数之一是节点集,则永远不要使用它。

  2. 尽可能避免使用 // 缩写--这可能会导致显著的低效,并且还有异常行为,对大多数人来说并不明显。


6

使用not(@tool)代替!@tool应该可以完成任务。如果您的XPath引擎不正常,您可以考虑使用count(@tool)=0,但这不是必要的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接