Search code examples
c#xmlxmldocumentselectsinglenodeselectnodes

SelectSingleNode returns null when tag contains xmlNamespace


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?


Solution

  • 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);