A few weeks back I was doing some pokin’ around the ol’ web regarding reading XML from somewhere (database, file-system, the trunk of your car) and into an .NET object.  In case you weren’t aware…it turns out .NET makes doing this type of work nothing short of trivial. 

<slightly off-topic background info>

That is, if you had XML that you [stole from MSDN] that looked like this…

<?xml version="1.0"?>
   <book>
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
...

…and you had an object that looked like..

public class Book{
    string author{get; set;}
    string title{get; set;}
    string genre{get; set;}
    decimal price{get; set;}
    date publish_date{get; set;}
    string description{get; set;}
}

You could do this…

XmlSerializerFactory xmlSerializerfactory = new XmlSerializerFactory();
XmlSerializer serializer = xmlSerializerfactory.CreateSerializer(typeof(book));
book myDeserializedBook = (book)serializer.Deserialize(responseStream);

And you magically have a populated instance of the book class with the values from the XML file above.

</slightly off-topic background info>

The first time you deserialize an object of a particular type, the framework creates an assembly of that type on-the-fly which incurs some overhead.  This is the same way the older, .NET Framework provided XmlSerializer works.  (This is also how I go the title for this post)  The difference is that XmlSerializerFactory is supposed to cache these assemblies the first time they are created.  Well, bad news kids, if you use any of the following constructors besides the first, the .NET Framework won’t cache the assembly. 

CreateSerializer(System.Type)
CreateSerializer(System.Type, string)
CreateSerializer(System.Type, System.Type[])
CreateSerializer(System.Type, System.Xml.Serialization.XmlAttributeOverrides)
CreateSerializer(System.Type, System.Xml.Serialization.XmlAttributeOverrides, System.Type[], System.Xml.Serialization.XmlRootAttribute, string)
CreateSerializer(System.Type, System.Xml.Serialization.XmlAttributeOverrides, System.Type[], System.Xml.Serialization.XmlRootAttribute, string, string, System.Security.Policy.Evidence)
CreateSerializer(System.Type, System.Xml.Serialization.XmlRootAttribute)
CreateSerializer(System.Xml.Serialization.XmlTypeMapping)

Daniel Cazzulino pointed this out, and I’m thankful to have come across his post in my XmlSerializerFactory investigation. 

I ended up going with code that resembles this with the exception of opting not to use the XmlSerializerFactory since it doesn’t seem like it buys me anything over the standard XmlSerializer if I’m not using the (System.Type) constructor.

Share this post :

 

Technorati Tags: ,,