How to use LINQ to parse XML

by Viper 2. June 2009 03:25

While working on Local Twitter application, I had to parse a very simple XML stream to create a business object. In classic XML days, we all used to do it using XPath or SAX or other related techniques. Xml to Linq and Linq to Xml provides a very intuitive way to perform parsing task. Lets look at the code snippet below.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
 <Ip>74.125.45.100</Ip>
 <Status>OK</Status>
 <CountryCode>US</CountryCode>
 <CountryName>United States</CountryName>
 <RegionCode>06</RegionCode>
 <RegionName>California</RegionName>
 <City>Mountain View</City>
 <ZipPostalCode>94043</ZipPostalCode>
 <Latitude>37.4192</Latitude>
 <Longitude>-122.057</Longitude>
</Response>

private SiteUser ProcessResponse(string strResp)
{
 StringReader sr = new StringReader(strResp);
 XElement respElement = XElement.Load(sr);
 string callStatus = (string)respElement.Element("Status");
 if (string.Compare(callStatus, "OK", true) != 0)
 {
  return null;
 }
 SiteUser user = new SiteUser() {IP = (string) respElement.Element("Ip"), 
 City = (string) respElement.Element("City"),
 Country =  (string)respElement.Element("CountryName"),
 CountryCode = (string)respElement.Element("CountryCode"),
 RegionCode =  (string)respElement.Element("RegionCode"),
 RegionName = (string)respElement.Element("RegionName"),
 PostalCode =  (string)respElement.Element("ZipPostalCode"),
 Latitude = (decimal)respElement.Element("Latitude"),
 Longitude = (decimal)respElement.Element("Longitude")};
 return user;
}

You can see from the code above, how easy the task is. You load up the XML string as StringReader and then use that to initialize XElement object. When you create XElement it is already at documentElement level. The rest of the API is self explanatory. You simple use Element method to access elements by their node names under a given XElement object.

Give your advice to big bosses and make money

Views: 6034

Tags: ,

LINQ | XML

Comments

7/23/2009 5:46:12 PM #

Daniel Steiger

Do you accept guest posts? I would love to write couple articles here.

Daniel Steiger United States

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli

By Categories