Saturday, March 10, 2012

Reading XML nodes Attributes values using XmlDocument and XPath classes in C#

Today's example will show the way to read attributes values using XMlDocument class and XPath class in C#.Net. And after retrieving the values will select a particular node based on Attribute value match. 

Customers.xml

<?xml version="1.0" encoding="utf-8" ?>
<Customers>
  <Customer name="Aryan Mehta" country="India"  
   emailid="aryanmehta@aryan.com"/>
  <Customer name="Steve Martin" country="Australia" 
   emailid="steve.martin@yahoo.com"/>
  <Customer name="Sandra Smith" country="Australia" 
   emailid="sandra.s@gmail.com"/>
  <Customer name="Jack Ryder" country="United States" 
   emailid="jack.ryder@yahoo.com"/>
</Customers>
  
Loading the customers xml into the XmlDocument object:

XmlDocument xDoc = new XmlDocument();
xDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");

//select a list of Nodes matching xpath expression
XmlNodeList oXmlNodeList = xDoc.SelectNodes("Customers/Customer");
  
Requirement 1: Retrieving all the customers details in Attributes Name,value format

//looping through the all the node details one by one
foreach (XmlNode x in oXmlNodeList)
{
  //for the current Node retrieving all the Attributes details
  string Name = x.Attributes["name"].Value;
  string Country = x.Attributes["country"].Value;
  string EmailId = x.Attributes["emailid"].Value;

  //displaying the customer details in console window
  Console.WriteLine("Name={0}, Country={1}, EmailId=
                    {2}",Name,Country,EmailId);                 
}


Output:-

Requirement 2: Retrieving all the customers details in Attributes Name,value format whose name starts with alphabet "S"

//looping through the all the node details one by one
foreach (XmlNode x in oXmlNodeList)
{
   // added a filter condition for
   //checking the letter "S" in the customer name
   if (x.Attributes["name"].Value.ToUpper().Contains('S'))
   {
     string Name = x.Attributes["name"].Value;
     string Country = x.Attributes["country"].Value;
     string EmailId = x.Attributes["emailid"].Value;
  
     Console.WriteLine("Name={0}, Country={1}, EmailId={2}", Name, 
     Country, EmailId);
   }
}

Output:-
As you can see in the output only those customers whose name starts with letter "S" has been displayed.

I have used Console.Write for writing the output to demonstrate the output retrieved. You can use any way the data is required to be displayed or stored in a collection.


Happy Coding.........