当标签包含 xmlNamespace 时,SelectSingleNode 返回 null
我正在将字符串加载到包含以下结构的 XML 文档中:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Include="clsWorker.cs" />
</ItemGroup>
</Project>
然后将所有内容加载到 XmlDocument
中:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(Xml);
然后出现以下问题:
XmlNode Node = xmldoc.SelectSingleNode("//Compile"); // returns null
当我删除 xmlns
时> 来自根元素(Project
)的属性,它工作正常。
如何让 SelectSingleNode
返回相关元素?
I'm loading a string into an XML document that contains the following structure:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Include="clsWorker.cs" />
</ItemGroup>
</Project>
Then I'm loading all into an XmlDocument
:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(Xml);
Then the following problem occurs:
XmlNode Node = xmldoc.SelectSingleNode("//Compile"); // returns null
When I remove the xmlns
attribute from the root element (Project
), it works fine.
How do I get SelectSingleNode
to return the relevant element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该在调用 SelectSingleNode():
You should use an XmlNamespaceManager in your call to SelectSingleNode():
直接取自 MSDN 上的
SelectSingleNode()
文档:接下来的示例代码是
它 不 as 如果 这个 会 是“隐藏 知识"。 ;-)
Taken right from the documentation of
SelectSingleNode()
on the MSDN:And the immediately following sample code is
It's not as if this would be "hidden knowledge". ;-)
这样你就不需要指定名称空间:
This way you don't need to specify namespace:
由于“ItemGroup”可能有多个“Compile”子项,并且您特别需要“Project/ItemGroup”的“Compile”子项,因此以下命令将返回所有所需的“Compile”子项,而不返回其他子项:
请注意,“msbld” :' 命名空间规范需要位于每个节点级别之前。
Since the 'ItemGroup' may have multiple 'Compile' children, and you specifically want the 'Compile' children of 'Project/ItemGroup', the following will return all of the desired 'Compile' children and no others:
Note that the 'msbld:' namespace specification needs to precede each node level.