XmlDocument.SelectSingleNode和xmlNamespace问题

时间:2010-11-13 07:26:07

标签: c# xml xmldocument selectsinglenode selectnodes

我正在将字符串加载到包含以下结构的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"); // return null

当我从根元素(Project)中删除xmlns属性时,它的工作正常, 如何改进我的SelectSingleNode以返回相关元素?

4 个答案:

答案 0 :(得分:80)

您应该在通话XmlNamespaceManager中使用SelectSingleNode()

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

答案 1 :(得分:17)

documentation of SelectSingleNode() on the MSDN开始:

  

注意
  如果XPath表达式不包含前缀,则假定为   namespace URI是空名称空间。 如果您的XML包含默认值   在命名空间中,您还必须添加前缀和名称空间URI   XmlNamespaceManager的;否则,您将无法选择节点。 For   更多信息,请参阅Select Nodes Using XPath Navigation

紧随其后的示例代码是

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com");
XmlNode book = doc.SelectSingleNode("//ab:book", nsmgr);

It's not as if this would behidden knowledge” 。 ; - )

答案 2 :(得分:3)

由于&#39; ItemGroup&#39;可能有多个编译&#39;孩子,你特别希望编译&#39;项目/项目组的孩子,以下将返回所有想要的&#39;编译&#39;孩子而不是其他人:

XmlDocument projectDoc = new XmlDocument();
projectDoc.Load(projectDocPath);
XmlNamespaceManager ns = new XmlNamespaceManager(projectDoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNodeList xnList = projectDoc.SelectNodes(@"/msbld:Project/msbld:ItemGroup/msbld:Compile", ns);

请注意&#39; msbld:&#39;命名空间规范需要在每个节点级别之前。

答案 3 :(得分:1)

这样您就不需要指定命名空间:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("your xml");
XmlNode node = xmlDoc.SelectSingleNode("/*[local-name() = 'Compile']");
XmlNode nodeToImport = xmlDoc2.ImportNode(node, true);
xmlDoc2.AppendChild(nodeToImport);