Loop through XML and retrieve all elements using C# (.NET)
XML is a wonderful invention readily accepted by the programming community. Nowadays, you will find most of the data as XML. How to make it in a readable / printable form. The obvious answer would be a XML transformation (using XSLT).
But here we will look into a simple way to extract contents of XML using C#
The XML File looks like the following:
< ?xml version="1.0" encoding="us-ascii" standalone="yes"? >
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "C:\ShasurData\ForBlogger\OldData\Sample.DTD" >
< !--Sample Invoice for GP GmbH-- >
< Invoice INVNo="INT03456" InvDate="15-09-2008 08:41:42" xmlns:d1p1="InvDate" >
< Items >
< Item >
< Name >Hex Socket Screw< /Name >
< Price >$4.25< /Price >
< Quantity >1000< /Quantity >
< /Item >
< Item >
< Name >Roll Bearing< /Name >
< Price >$6.15< /Price >
< Quantity >1200< /Quantity >
< /Item >
< /Items >
< /Invoice >
We use the following code to loop through the nodes and extract the elements
private static void ReadXMLEXample()
{
XmlDocument XDoc = new XmlDocument();
XDoc.Load(@"C:\ShasurData\ForBlogger\OldData\Sample.xml");
XmlNodeList XNodeList = XDoc.SelectNodes("//Items/Item");
Console.WriteLine("{0}\t{1}", "Name","Price");
foreach (XmlElement XElement in XNodeList)
{
Console.WriteLine("{0}\t{1}", XElement["Name"].InnerText.ToString(), XElement["Price"].InnerText.ToString());
}
}
The output will be :
cool stuff, check out next generation Workflow for .net developers at http://www.cDevWorkflow.com
ReplyDelete