Wednesday, March 21, 2007

Using XML Serialization

While finishing our Interactive Course project, we decided we had to do something about the rather oldschool way we parsed our XML files. The code to parse an XML file was divided into two classes, a parser and a schema validator, totalling for some 150 lines of code. Luckily Kurt (who is guiding our internship) let us in on the whole XmlSerialization thingie...



Click for a larger view...

Using the xsd.exe program, which can be easily found in the Visual Studio directory, we made an XSD scheme for our xml file. After the XSD was created by the program, we fed the program the XSD and a serializable class is created for our XML file. After we had imported this class file into our solution, the code to load the course from an XML file looked like this:

XmlSerializer xs = new XmlSerializer(typeof(Course)); FileStream fstrm = new FileInfo(fileName).OpenRead(); return (Course)xs.Deserialize(fstrm);

These 3 lines replace the 150+ lines we coded to parse and validate the XML file, if only we would have known ;-) Luckily, now you do! So don't go using the good old (even deprecated) XmlReader class, serialization is the next best thing!

No comments: