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.
How to convert xml file into a String object
Error in xml namespace tag declaration
ADO.Net Dataservice Error: Request Error Server Encountered an error processing request
How to plan CCSP Exam preparation
Develop a MongoDB pipeline to transform data into time buckets
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2025 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use