Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
The XmlSerializer is your new best friend when it comes to
serializing objects to XML documents. It will save you from writing code using
with the XmlDocument or XmlTextReader/-Writer classes to save and restore
objects. Many of us are probably familiar developing serialization solutions
using an XML parser directly, e.g. if you have an application sending the data
over the internet. In your application, the data you want to send is lives
encapsulated within objects, but you need to serialize the objects in order to
send the data. You probably added boiler-pate code to these classes to persist
fields to XML using a DOM Document class.
If your application also received data in XML format you probably wrote more
lines of boiler-plate code to parse the received XML and set the properties on
your objects.
Now the XmlSerializer does it all for you. It handles the transformation
both ways and, to make life even better, we do not even have to create the
classes to serialize ourselves. If we have an XML schema describing the data
layout of our transfer format we can generate .NET classes corresponding to the
complex types in the schema with the Framework’s XSD schema definition tool.
You can find all about the XSD tool in Appendix C. In the following sections of
this chapter we will learn how to use the XmlSerializer, and how we need to
design classes so the XmlSerializer can use them.
Let’s start out developing a class for the XmlSerializer to
process. The garage example document used throughout the first part of this
book contained car element nodes with attributes to store some information
about a car. That’s a good candidate for a class right there.
When we develop .NET classes we no longer need to worry about
writing methods to serialize an object to XML. This functionality is built
directly into the .NET Framework. Let’s start with a very simple
Car class. Each Car object needs members for make, model and
the year the car was built.
Listing 9.1:
example class to use with the XmlSerializer