问题描述
什么是XPath(在C#中的API XDocument.XPathSelectElements(XPath中,nsman),如果它事项)查询所有MyNodes从这个文件?
What is the XPath (in C# API to XDocument.XPathSelectElements(xpath, nsman) if it matters) to query all MyNodes from this document?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<MyNode xmlns="lcmp" attr="true">
<subnode />
</MyNode>
</configuration>
- 我试过
/配置/ MYNODE
这是错误的,因为它忽略了命名空间 - 我试过
/配置/ LCMP:MYNODE
这是错误的,因为LCMP
是URI,而不是前缀。 - 我试过
/配置/ {LCMP} MYNODE
这失败,因为附加信息:'/配置/ {LCMP} MYNODE'有一个无效的令牌
- I tried
/configuration/MyNode
which is wrong because it ignores the namespace. - I tried
/configuration/lcmp:MyNode
which is wrong becauselcmp
is the URI, not the prefix. - I tried
/configuration/{lcmp}MyNode
which failed becauseAdditional information: '/configuration/{lcmp}MyNode' has an invalid token.
编辑:我不能使用 mgr.AddNamespace(东风,LCMP);
因为一些回答者有建议。这要求XML解析程序都知道我打算使用时间提前的命名空间。由于这是为了适用于任何的源文件,我不知道哪个名字空间手动添加前缀。这似乎是 {我的URI}
是XPath语法,但微软并没有理会执行该...真的吗?
I can't use mgr.AddNamespace("df", "lcmp");
as some of the answerers have suggested. That requires that the XML parsing program know all the namespaces I plan to use ahead of time. Since this is meant to be applicable to any source file, I don't know which namespaces to manually add prefixes for. It seems like {my uri}
is the XPath syntax, but Microsoft didn't bother implementing that... true?
推荐答案
的配置
元素是在未命名的命名空间,且MYNODE绑定到 LCMP
命名空间没有命名空间前缀。
The configuration
element is in the unnamed namespace, and the MyNode is bound to the lcmp
namespace without a namespace prefix.
这 XPATH 语句将允许您解决 MYNODE
,而不必声明的 LCMP
命名空间或在XPATH使用一个命名空间前缀元素:
This XPATH statement will allow you to address the MyNode
element without having declared the lcmp
namespace or use a namespace prefix in your XPATH:
/configuration/*[namespace-uri()='lcmp' and local-name()='MyNode']
它匹配的是配置
的任何子元素,然后使用谓词滤波器用的和的功能限制它的 MYNODE
元素。
It matches any element that is a child of configuration
and then uses a predicate filer with namespace-uri()
and local-name()
functions to restrict it to the MyNode
element.
如果您不知道哪些命名空间的URI将用于元素,那么你可以让在 XPATH 更通用的,只是匹配的本地名称()
:
If you don't know which namespace-uri's will be used for the elements, then you can make the XPATH more generic and just match on the local-name()
:
/configuration/*[local-name()='MyNode']
但是,在运行匹配不同的词汇不同的元素(绑定到不同的命名空间的URI)碰巧使用相同的名称的风险。
However, you run the risk of matching different elements in different vocabularies(bound to different namespace-uri's) that happen to use the same name.
这篇关于我如何使用XPath与没有前缀的默认命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!