August 19, 2019

Select XML Nodes with XML Namespaces from an XmlDocument and XDocument

To select XML Nodes with Namespace we have to use type XmlNamespaceManager. The AddNamespace() method of XmlNamespaceManager object takes two arguments: one is prefix and the second is the Uri.

Let's say we have following xml:

 <md:ProductOutput xmlns:cb="http://mydomain.com/report/">
   <md:Header>
  <md:Child1 SubjectStatus="">
   Some text for Child1
  </md:Child1>     
   </md:Header>
   <md:Body DocumentID="356d6d32-5755-4ffb-a8b8-8932577526dd">
  <md:Child2>
   Some test for Child2
  </md:Child2>
   </md:Body>
 </md:ProductOutput>

Using XmlDocument:

When selecting nodes from XmlDocument object, you have to use an instance of XmlNamespaceManager class. To select the node md:Header, we will pass the XmlNamespaceManager's instance to SelectSingleNode method of XmlDocument.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString); // xmlString variable contains above xml

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("md", "http://mydomain.com/report/");

XmlNode nodeHeader = xmlDocument.SelectSingleNode("//md:Header", nsmgr);
//nodeHeader contains the required node

Using XDocument:

To select the node elemment from XDoocument, we have to concatenate node name (Header) with the XNamespace and pass this to Element() method of XDocument.Root Element.

var xdoc = XDocument.Parse(xmlString); // xmlString variable contains above xml
XNamespace ns = "http://mydomain.com/report/";

var elementHeader = xdoc.Root.Element(ns + "Header");
//elementHeader contains the required element

No comments:

Post a Comment