Introduction
In this article we will discuss how to read XML data using XmlDocument object. We can read data through SelectNodes() method which returns XMlNodeList object and it contains list of nodes as per xpath string. However if XML data contains namespace then normal code won't work. We need to create XmlNamespaceManager object and inject with XmlDocument object.
We can also read XML data through LINQ. If you are curious to know how to fetch XML data through LINQ then visit here.
Using Code
Let's define XML data which contains namespace attribute. In the following XML data, Body tag contains namespace attribute as xmlns which contains value as:
"http://schemas.xmlsoap.org/soap/envelope/" .
- string xmlContent = @"<?xml version='1.0' encoding='utf-8'?>
- <Body xmlns='http://schemas.xmlsoap.org/soap/envelope/'>
- <Site Id='1'>
- <Url>http:
- <Description>A social community for developers and programmers.</Description>
- </Site>
- <Site Id='2'>
- <Url>http:
- <Description>Itwas formed to provide developers with a place to meet.</Description>
- </Site>
- </Body>";
The following code-snippet defines to read XML data. Firstly, it creates
XmlDocument object and load xml content to it through
LoadXml() method. Secondly, it creates XmlNamespaceManager and add namespace using
AddNamespace() method. Thirdly, it injects NamespaceManger object with SelectNodes() method and returns XmlNodeList object. Lastly it loops over the nodelist and get all required values. Result is shown in Figure 1.
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(xmlContent);
-
-
- XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
- nsmgr.AddNamespace("ns", "http://schemas.xmlsoap.org/soap/envelope/");
-
-
- XmlNodeList xNode = doc.SelectNodes("ns:Body/ns:Site", nsmgr);
-
- foreach (XmlNode xndNode in xNode)
- {
- string Id = xndNode.Attributes["Id"].InnerText;
- Console.WriteLine("Id: " + Id);
-
- string Url = xndNode["Url"].InnerText;
- Console.WriteLine("Url: " + Url);
-
- string Description = xndNode["Description"].InnerText;
- Console.WriteLine("Description: " + Description);
- }
Output Figure 1: Result of reading data from XML
Suppose there is a requirement that you want to fetch site details whose Id is 1. In the following code we need to change only in our filtering string(xpath string) - "
[@Id='1']" is added.
- XmlNodeList xnList = doc.SelectNodes("ns:Body/ns:Site[@Id='1']", nsmgr);
- foreach (XmlNode xn in xnList)
- {
- string Url = xn["Url"].InnerText;
- string Description = xn["Description"].InnerText;
- }
Conclusion In this blog we discussed how to read XML data when it contains namespace. Also we discussed how to query/filter XML data using XmlDocument object.