当标签包含 xmlNamespace 时,SelectSingleNode 返回 null [英] SelectSingleNode returns null when tag contains xmlNamespace

查看:32
本文介绍了当标签包含 xmlNamespace 时,SelectSingleNode 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个字符串加载到包含以下结构的 XML 文档中:

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>

然后我将所有内容加载到 XmlDocument 中:

Then I'm loading all into an XmlDocument:

XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(Xml);

然后出现如下问题:

XmlNode Node = xmldoc.SelectSingleNode("//Compile"); // returns null

当我从根元素 (Project) 中删除 xmlns 属性时,它工作正常.

When I remove the xmlns attribute from the root element (Project), it works fine.

如何让 SelectSingleNode 返回相关元素?

How do I get SelectSingleNode to return the relevant element?

推荐答案

您应该使用 XmlNamespaceManager 在您对 SelectSingleNode() 的调用中:

You should use an XmlNamespaceManager in your call to SelectSingleNode():

XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNode node = xmldoc.SelectSingleNode("//msbld:Compile", ns);

这篇关于当标签包含 xmlNamespace 时,SelectSingleNode 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆