Wednesday, July 2, 2008

Read XML into string using LINQ

LINQ has made programmer’s life much easier and taken away pains of parsing XML nodes using XPath or Xml DOM. In this thread, we’ll see an example of reading XML contents into string variables using LINQ. Suppose we have sample XML Message which looks like this

<Input>

<City>Ludhiana</City>

<State>Punjab</State>

<Country>India</Country>

<Phone>01613535366</Phone>

</Input>


Now you want to parse the contents of these XML elements and retrieve them into various string objects. Next code is exactly to serve this purpose


//include these namespaces
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.IO;

//real code to read strings
string xml = "..xml above as a string..";
TextReader tr = new StringReader(xml);
XDocument xmlDoc = XDocument.Load(tr);
XElement inputXmlElement = xmlDoc.Element("Input");
string city = (string) inputXmlElement.Element("City");
string state = (string) inputXmlElement.Element("State");
string country = (string) inputXmlElement.Element("Country");
string phone = (string) inputXmlElement.Element("Phone");

You can notice, how dramatically the lines of Code has decreased.

Note: For using LINQ in VS 2005 you have some prerequisites i.e. you need to install LINQ extensions first.

1 comment:

Anonymous said...

This helped me. Thanks!

Alternatively, you could:

string xml = "..xml above as a string..";
XDocument xmlDoc = XDocument.Parse(xml);