xml 如何在没有特定属性的所有元素上使用 XPath 进行过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/812090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:28:09  来源:igfitidea点击:

How to filter with XPath on all elements without a specific attribute

xmlxpath

提问by lyngbym

My XPath is a little bit rusty... Let's say I have this simple XML file:

我的 XPath 有点生疏……假设我有这个简单的 XML 文件:

<?xml version="1.0" encoding="utf-8" ?>
<States xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<States>
<StateProvince name="ALABAMA" abbrev="AL" />
....
<StateProvince name="AMERICAN SAMOA" abbrev="AS" territory="true"  />
</States>
</States>

I would like to run a simple XPath query to parse out all of the true states (so don't pull in states where territory = true). I tried \StateProvince[@territory!='true'] but I got zero. Other variations seem to be failing. This seems like it should be simple, but not finding what I want.

我想运行一个简单的 XPath 查询来解析所有真实的状态(所以不要拉入领土 = 真实的状态)。我试过 \StateProvince[@territory!='true'] 但我得到了零。其他变体似乎失败了。这看起来应该很简单,但没有找到我想要的。

Any help appreciated.

任何帮助表示赞赏。

回答by Dimitre Novatchev

One XPath expression that selects the wanted elements:

一种选择所需元素的 XPath 表达式

        /*/States/StateProvince[not(@territory='true')]

        /*/States/StateProvince[not(@territory='true')]

Do notethat one must avoid the //abbreviation whenever possible as it causes the whole document (subtree rooted at the context node) to be scanned.

请注意必须//尽可能避免使用缩写,因为它会导致扫描整个文档(以上下文节点为根的子树)

The above XPath expression avoids the use of the//abbreviationby taking into account the structure of the originally-provided XML document.

上面的XPath 表达式通过考虑到原始提供的XML 文档的结构来避免使用缩写//

Only if the structure of the XML document is completely unknown (and the XPath expression is intended to be used accross many XML documents with unknown structure) should the use of the //abbreviation be considered.

只有当 XML 文档的结构完全未知(并且 XPath 表达式旨在用于许多结构未知的 XML 文档)时,才应考虑使用//缩写

回答by Jordan S. Jones

You are very close:

你非常接近:

//StateProvince[not(@territory) or @territory != 'true']

Should get you the result you want.

应该让你得到你想要的结果。

回答by pgb

This should work:

这应该有效:

//StateProvince[not(@territory='true')]