Recently I've been working on a project that uses third party RESTful service a lot. The main response format of the service is XML, I found it is a big headache to parse the data using XmlDocument, so wondering if it can be easily done by using LINQ to XML. The answer is YES, here comes the code snippet...
1, Download the Raw Xml to XDocument object...
XDocument xDoc = XDocument.Load([RESTful API Url]);
2, Get the root element from XDocument...
XElement rootElement = xDoc.Root.Element(XName.Get("rootElement", "Namespace"));
Note here we are using XName, you can either use XName.Get("{Namespace}rootElement") or XName.Get("rootElement", "Namespace"). One thing I would like to mention is if the XML does not has namespace, you may directly get the element by using xDoc.Root.Element("rootElement").
3, LINQ to child elements in the root element...
XName xname = XName.Get("item", strNamespace);
var q = from row in rootElement.Descendants(xname)
select new Item((long)row.Element(XName.Get("itemId", "Namespace")), (string)row.Element(XName.Get("title", "Namespace")));
Note: The Item class is a business object that contains the data element.
4, Now handle the result set, below example is just simply bind the result to a repeater control...
this.rptMostViewedItem.DataSource = q;
this.rptMostViewedItem.DataBind();
As a reference, you can also refer to my previous post: LINQ to XML in 2 minutes