How to use LINQ to parse XML

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.

Search

Social

Weather

-0.8 °C / 30.6 °F

weather conditions Mist

Monthly Posts

Blog Tags