Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 557
Shlomi Komemi Avatar asked Nov 13 '10 07:11

Shlomi Komemi


1 Answers

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); 
like image 137
Frédéric Hamidi Avatar answered Sep 17 '22 21:09

Frédéric Hamidi