-
Silverlight : goodbye XmlDocument, hello XDocument !
Posted on August 15th, 2009 2 comments
I just started my initiation to Silverlight and noticed while following the workshops of the MSDN Coachs program that a class XDocument was used to parse some Xml. So I thought at first “what’s that new class ? Why didn’t they use XmlDocument ?”.Well, simply because it’s gone ! The reason of that, found on the forums of the official Silverlight website, is that because Linq to Xml is the recommended way to work with Xml in Silverlight, so System.Xml.XmlDocument was removed and is now succeeded by System.Xml.Linq.XDocument.
For those who’re new to Linq to Xml, here’s a quick example of what you can perform with that powerful technique :
1. The class, using auto-implemented properties
public class DiggStory
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string HrefLink { get; set; }
public int NumDiggs { get; set; }
public string Thumbnail { get; set; }
}
2. Using Linq to Xml
XDocument xmlStories = XDocument.Parse(xmlContent);
var stories = from story in xmlStories.Descendants("story")
where story.Element("thumbnail") != null
select new DiggStory
{
Id = (int) story.Attribute("id"),
Title = (string) story.Attribute("title"),
Description = (string) story.Attribute("description"),
Thumbnail = (string) story.Attribute("thumbnail"),
HrefLink = (string) story.Attribute("link"),
NumDiggs = (int) story.Attribute("diggs")
};
3. Conclusion
Advantages of this method is that :
- It’s way more elegant than classic XPath strings
- You get a collection of strongly typed items
- It’s very easy to perform databinding on the basis of the item properties
Make good use of it


