My longest-standing VS.NET RegEx question, answered LINQ’s “var” keyword – the new obfuscation method of choice

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…

3 Responses to “The crowning jewel in XLinq”

  1. The “X” classes and the “Xml” classes will be reconciled in the actual release of LINQ to XML. There will be bridge classes that let you setup an XmlReader over LINQ to XML and a XmlWriter into DOM (or vice versa), let you setup an XPathNavigator over a LINQ to XML tree so that you can use XPath/XSLT if you prefer, and to let you write the results of an XSLT transform into a LINQ to XML tree … all without serializing to XML text.

  2. >> I’ll have to .Save this doc into a memory stream and reload it. Sigh…

    We plan to implement a set of classes that will allow you to integrate XLinq with the rest of the system.xml stack using XPathNavigator, XmlReader and XmlWriter. Stay tuned…

  3. I love the functional stuff that’s making its way into C# at the moment, and the bridge classes are great news. Thanks, chaps :)

Leave a Reply

(required)

(required)

© 2014 ZephyrBlog Suffusion theme by Sayontan Sinha