Tuesday, March 30, 2004

System.Xml 2.0 = Coolness

I was just reading this (via Aaron), and saw this piece of code:






if (reader.ReadToDescendant("book"))
{
   do
   {
      Book book = (Book)(reader.ReadAsObject(typeof(Book)));
      ProcessBook (book) // Do some processing on the book object
   } while (reader.ReadToNextSibling("book"));
}






OK, the highlighted bit is just so cool I can barely wait to start using it.


In case it's not obvious from the code, they've married XmlSerializer and XmlReader so you can stream through a document, yanking out objects as you go. They've also added the even cooler ability to write objects into an XmlWriter stream. To resurrect a saying from my youth: mint!

7 comments:

  1. Ok, that's pretty cool, and I could use it right now.

    Something else that would be cool is a way to mate XPath expressions with XmlSerializer. So,

    Book book = (Book)(xpathNav.SelectAsObject("/root/book", typeof(Book)));

    What do you think?

    ReplyDelete
  2. A great idea. From what I can see, Whidbey supports this scenario in a very few lines of code...just not in one line of code.

    ReplyDelete
  3. I read the ADO.NET and XML v2.0 book, but it either wasn't in there or I missed it. Anyway, this is very interesting.

    ReplyDelete
  4. That's excellent! But I have one question: why can't I do this?:

    Book book = reader.ReadAsObject < Book > ();

    What's with all this casting, in a world with generics? (Of course what you really want is for the template parameter to be inferred, but sadly you cannot infer template arguments from function return types.)

    ReplyDelete
  5. Is there a big difference from using the XmlSerializer?



    [code] //where the node is the object-"root"

    XmlSerializer serializer = new XmlSerializer(typeof(MyClass));



    XmlNodeReader reader = new XmlNodeReader(node);

    object fetchedObject = serializer.Deserialize(reader);

    ReplyDelete
  6. Not significantly different, no. But isn't it nice when common paradigms are captured? It shows they "get it".

    ReplyDelete
  7. More functionel classes are always welcome :-)

    ReplyDelete