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
string Name = x.Attributes["name"].Value;
//displaying the customer details in console window
//looping through the all the node details one by one
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 Country = x.Attributes["country"].Value;
string EmailId = x.Attributes["emailid"].Value;
Console.WriteLine("Name={0}, Country={1}, EmailId=
{2}",Name,Country,EmailId);
}
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);
}
}
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.........
Check this one, many methods to read xml file
ReplyDeleteling