REST with LINQ to XML
With LINQ to XML, what I have learned so far, it's awesome, it is not only the first class concept of processing XML data, but also let you process a complex XML doc in the most simplest and readable way.
I have a project called, Linq.Flickr , and I often need to process XML data for REST query.
To show a simple example of LINQ to XML, lets take a REST response from a Flickr method called flickr.people.getUploadStatus and see how it is processed.
<user id="12037949754@N01" ispro="1"> <username>Bees</username> <bandwidth maxbytes="2147483648" maxkb="2097152" usedbytes="383724" usedkb="374" remainingbytes="2147099924" remainingkb="2096777" /> <filesize maxbytes="10485760" maxkb="10240" /> <sets created="27" remaining="lots" /> </user>
Before .net 3.5. it could have been done by GetElementyByTagName("users") - > inside the while loop getting the element, reading value, storing it in private variables , going to next sibling and repeat, if nested , then take the first child and so forth. But , in .net 3.5 using LINQ , the translation is not only just like XML itself, moreover , in XElement.Load , we can directly pass the REST query string.
So, Two, steps to do a REST with LINQ
- Build the URL and pass it to XElement.Load
- Parse the response and take necessary actions.
For example, for the above XML, I wrote something like below, in PhotoRepository.cs, that does a selective parsing.
try
{ XElement element = GetElement(##REQUEST URL##);
People people = (from p in element.Descendants("user")
select new People
{
Id = p.Attribute("id").Value ?? string.Empty,
IsPro =
Convert.ToInt32(p.Attribute("ispro").Value) == 0 ? false : true,
BandWidth =
(from b in element.Descendants("bandwidth")
select new BandWidth
{
RemainingKB =
Convert.ToInt32(b.Attribute("remainingkb").Value),
UsedKB = Convert.ToInt32(b.Attribute("usedkb").Value)
}).Single<BandWidth>()
}).Single<People>();
return people;
}
catch (Exception ex)
{
throw new ApplicationException("Could not process response", ex);
}
Note :GetElement is a local method that does a XElement.Load, with some validation check.
Here my Client-Side object looks like
People
Id
IsPro
BandWidth
RemainingKB
UsedKB
The most interesting thing is, everything is done on the fly , no loop, no intermediate result tracking, no headache of sibling and first child.Overall, the code has a high point in terms of readability.
Take that !!