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

查看:93
本文介绍了当标签包含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

当我删除 xmlns 根元素( Project )中的属性,它可以正常工作。

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 -us / library / h0hw012b.aspx> 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天全站免登陆