Windows Phone Developers

Tuesday, December 16, 2008

How to Get All Elements of an XML using C# (.NET)

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 :




Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

1 comment:

  1. cool stuff, check out next generation Workflow for .net developers at http://www.cDevWorkflow.com

    ReplyDelete

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005