Deserialize + serialize an InfoPath Form loses the processing instructions


Using xsd.exe you can generate a Class from your form schema (xsd) and then deserialize a form to an instance of that class. This makes it a lot easier to interact with its data.

CS class based on XSD

The code for serialization and deserialization might look like this:

public static T Deserialize<T>(Stream s)
{
T result = default(T);
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    using (XmlTextReader reader = new XmlTextReader(s))
    {
         result = (T)serializer.Deserialize(reader);
    }
    s.Close();
    return result;
}
public static T Deserialize<T>(string s)
{
    return Deserialize<T>(new MemoryStream(Encoding.UTF8.GetBytes(s)));
}
public static string Serialize<T>(T o)
{
string result = null;
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlWriterSettings settings = new XmlWriterSettings(); 
    settings.Indent = true;
    settings.Encoding = Encoding.UTF8;
    using (MemoryStream stream = new MemoryStream()) 
    {
         using (XmlWriter writer = XmlTextWriter.Create(stream, settings))
         {
             serializer.Serialize(writer, o);
         }
         stream.Flush(); 
         result = Encoding.UTF8.GetString(stream.ToArray());
    }
    return result; 
}

However you lose the original processing instructions at the top of the XML file. If you want to keep those either do custom serialization using an XmlWriter or do some kind of merge code with the original XML and the XML coming from serialization.

InfoPath XML Processing Instructions

Quite obvious if you think about it but I keep forgetting it :)

 


Links to this post

Comments

CAPTCHA Image Validation