It’s not the fact that you can query XML documents in-memory using a SQL-like syntax (hey, I already had XPath, thanks all the same).

It’s the fact that you can now create an XML document, for use in an example, where the C# code structure used to create the document mirrors almost exactly that of the resulting output document.

This is brought about by the ancient magic of variable parameter lists and well thought-out constructor overloads, and whoever’s responsible, I’d like to buy him a drink and look after his cat while he’s on holiday. This technique sits right between ugly raw DOM hacking (of which, I confess, I have done much) and beautifully-generated but hard-to-keep-in-sync XML Data Binding.

This is from the LINQ hands-on labs:

public static XDocument CreateDocument()
{
   // create the document all at once
   return new XDocument(
      new XDeclaration("1.0", null, null),
          new XElement("organizer",
             new XElement("contacts",
                 new XElement("contact", new XAttribute("category", "home"),
                 new XElement("name", "John Smith")),
                 new XElement("contact", new XAttribute("category", "home"),
                 new XElement("name", "Sally Peters")),
                 new XElement("contact", new XAttribute("category", "work"),
                 new XElement("name", "Jim Anderson")))));
}

Wonderful, n’est pas? The only shame is that the “X” classes are a little divorced from the rest of the XML namespaces; their primary purpose is to provide something for LINQ to talk to. So if I do want to use XPath, I’ll have to .Save this doc into a memory stream and reload it. Sigh…

© 2014 ZephyrBlog Suffusion theme by Sayontan Sinha