Home >Backend Development >C++ >How to Select XML Nodes with Namespaces Using C#?

How to Select XML Nodes with Namespaces Using C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-07 20:27:41571browse

How to Select XML Nodes with Namespaces Using C#?

Problems encountered when selecting XML nodes with namespaces in C#

Consider an XML document containing namespaces with the following structure:

<code class="language-xml"><?xml version="1.0" encoding="utf-8"?><project defaulttargets="Build" toolsversion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><itemgroup><compile include="clsWorker.cs"></compile></itemgroup></project></code>

If you try to retrieve a SelectSingleNode node using the Compile method without specifying a namespace, null will be returned:

<code class="language-csharp">XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(Xml);

XmlNode node = xmldoc.SelectSingleNode("//Compile"); // 返回null</code>

Solution: Use XmlNamespaceManager

In order to correctly retrieve the Compile node if the root element has a namespace, XmlNamespaceManager should be used:

<code class="language-csharp">XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNode node = xmldoc.SelectSingleNode("//msbld:Compile", ns);</code>

By adding a namespace manager and specifying the correct namespace prefix (in this case "msbld"), the SelectSingleNode method will successfully locate and return the required node.

The above is the detailed content of How to Select XML Nodes with Namespaces Using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn