I'm loading a string to 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 im loading all into xmldocument :
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(Xml);
then the following problem occurs :
XmlNode Node = xmldoc.SelectSingleNode("//Compile"); // return null
when i remove the xmlns attribute from the root element(Project) its working fine, how can i improve my SelectSingleNode to return the relevant element ?
Taken right from the documentation of
SelectSingleNode()
on the MSDN:And the immediately following sample code is
It's not as if this would be "hidden knowledge". ;-)
Since the 'ItemGroup' may have multiple 'Compile' children, and you specifically want the 'Compile' children of 'Project/ItemGroup', the following will return all of the desired 'Compile' children and no others:
Note that the 'msbld:' namespace specification needs to precede each node level.
You should use an XmlNamespaceManager in your call to SelectSingleNode():
This way you don't need to specify namespace: