12 October 2007

XML Serialization

I've been having to do some custom serialization in BizTalk and wanted to share some lessons learnt:

The System.Xml.Serialization.XmlSerializer class does the serializing and deserializing of class objects. There are some constraints that the class must observe:
1) Only public properties will be serialized, private ones are ignored totally
2) The class must be public too and it needs a parameterless constructor

Serialization example:

MyClass myClass = new MyClass();
FileStream myFileStream = new FileStream(@"C:\output.xml", FileMode.Open, FileAccess.Write);

XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
serializer.Serialize(myFileStream, myClass);


If you have a schema for your xml data, use the xsd utility to generate the class:
C:\Program Files\Microsoft Visual Studio 8\VC\xsd MySchema.xsd /classes

I'll comment more about using the IXmlSerializable interface in the future (note that the ReadXml method needs to rehydrate inner objects), but for now thats all.

No comments: