Accessing xml as objects in .Net

One of the thing I hate the most in the .Net Framework is System.Xml.XmlNode and all its siblings. It's so cumbersome to work with, resulting an almost unreadable code. Apologies for not coming up with a consistent example, I might revisit this post one day to clean it up.

public void ReadDocument(XmlReader reader)
  // read (pull) the next node in document order
  while (reader.Read())
    // get the current node's (namespace) name
    String sNodeName = (reader.NodeType == XmlNodeType.Element ||
      reader.NodeType == XmlNodeType.EndElement) ?
      reader.NamespaceURI + "#" + reader.Name : reader.Name;


taken from XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation

LINQ to XML makes it slightly better:

var contacts = from c in contacts.Elements("contact")
   select new XElement("contact",
      new XElement("phoneNumbers", c.Elements("phone"))

Taken from .NET Language-Integrated Query for XML Data

But working in just plain native code works way better for me. Hence, I always generate a proxy class for it. I can constantly work with nothing but objects. There will be no more XmlReader mess.

Generating a proxy class
On Vs2008 command prompt:

xsd /c /n:[namespace] [xsd ..]

for e.g

xsd /c /n:AskBobo.Blog.Feeds some-feeds.xsd some-types.xsd

/c = generate class
/n = namespace
And a bunch of xsd

This will produce proxy classes which then you can integrate into the project.

Integrating it in to the project
Simply copy the resulting classes into the solution, and include in project.

Using it
The idea is to instantiate a reader and deserialize the content to a Plain Old CLR Object (POCO). Like so:

var article = (article) (new XmlSerializer(typeof (article))).Deserialize(reader);

now you have access to all the properties directly as objects instead of all the annoying System.Xml.XmlNode stuff.

Console.Write( );
foreach (Sibling sibling in article.siblings)
  Console.Write( );

Isn't that much more beautiful?