Linq (and all its flavors) will come out with .Net 3.5 and Visual Studio 2008. Along with the Xml support are classes such as XDocument, XElement, XAttribute, etc. What’s interesting about XElement in particular is that it allows us to load some Xml from many sources and query into it. Depending on your experience with XPath, an Xml Linq query may be easier to write AND read.
Let’s look at a sample Linq to Xml query. I’m going to use my blog’s RSS feed, http://feeds.feedburner.com/jeffreypalermo.
Let’s start simple. We’ll read in the Xml from the RSS feed and enumerate through all the posts (or “items” in the RSS world).
XElement rssFeed = XElement.Load(@"http://feeds.feedburner.com/jeffreypalermo");
var items = from item in rssFeed.Elements("channel").Elements("item")
select item;
Console.WriteLine(items.Count());
foreach (object o in items){
Console.WriteLine(o);}
Note that we are merely reading in the feed into an XElement and then selecting all item nodes from the document.
That’s pretty interesting that we can filter to only the “item” nodes that quickly, but what if I want to find the posts with the author of “Jeffrey Palermo” (never mind that this is my feed, but imagine it was a composite feed).
XNamespace dc = "http://purl.org/dc/elements/1.1/";
XElement rssFeed = XElement.Load(@"http://feeds.feedburner.com/jeffreypalermo");
var items = from item in rssFeed.Elements("channel").Elements("item")
where item.Element(dc + "creator").Value == "Jeffrey Palermo"
select item;
foreach (object o in items){
Console.WriteLine(o); }
I gave this example to illustrate how to use the XNamespace class to help filter in nodes that declare a namespace prefix such as “dc:creator” in an RSS feed. Note the “where” clause in my Linq query.
And more like using XNamespace, creating transformation using Custom Type Collection with anonymous type, turn the anonymous type to a concrete type.