来自带有命名空间前缀的 xml 的 xpath 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3931817/
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
xpath expression from xml with namespace prefix
提问by Chaitanya
I could not get the following xpath expression to work when the xml path namespace prefix set.
设置 xml 路径命名空间前缀时,我无法使以下 xpath 表达式起作用。
/bk:BookStore/bk:Books/bk:Book[text()='Time Machine']
/bk:BookStore/bk:Books/bk:Book[text()='Time Machine']
XML is:
XML 是:
<BookStore xmlns:bk="http://www.bookstore.com/book#">
<bk:Books>
<bk:Book id="1">Time Machine></bk:Book>
</bk:Books>
</bk:BookStore>
回答by Ivivi Vavava
Or even better (and more portable), without the unnecessary prefix:
或者甚至更好(更便携),没有不必要的前缀:
/*/*[local-name()='Books'] ... and so on
The function local-nameignores any prefix, which, as correctly stated by commenters, can vary.
该函数会local-name忽略任何前缀,正如评论者正确指出的那样,这些前缀可能会有所不同。
回答by Dimitre Novatchev
Without more information about the host language(in which you attempt to evaluate XPath expressions) it is not possible to provide an useful recommendation.
如果没有关于宿主语言(您尝试在其中评估 XPath 表达式)的更多信息,就不可能提供有用的建议。
Generally, one needs to "register" a namespace with a namespace manager and this also associates a prefix to the registered namespace. Then, using this NamespaceManager object as an argument to the XPath-evaluation method, one can specify as argument to this method an XPath expression that contains names prefixed by that particular prefix.
通常,人们需要使用命名空间管理器“注册”一个命名空间,这也将前缀与注册的命名空间相关联。然后,使用这个 NamespaceManager 对象作为 XPath 评估方法的参数,可以指定一个 XPath 表达式作为该方法的参数,该表达式包含以该特定前缀为前缀的名称。
Workarounds:
解决方法:
/*/*[name()='bk:Books']/*[name()='bk:Book' and text()='Time Machine']

