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 last class we discuss in the context of the XmlSerializer is
the DataSet. We have learned all about how to store and access XML data in a
DataSet object in chapter 8. Now it’s time to learn how the XmlSerializer serializes
and deserializes DataSet objects, because it’s different from anything else we
have learned so far. Fasten your seat-belt, here we go.
The .NET architects wanted the DataSet class to become the
preferred vehicle to transmit data through WebServices. Since efficiency is an
important aspect in the transmission of data they designed a special (XML
based) format to transfer DataSets data, which only transmits the changes since
a DataSet was loaded. The format is called a DiffGram. Since ASP.NET WebServices create and parse SOAP messages
with the XmlSerializer, the serializer was now on the hook to serialize DataSet
object to the DiffGram format instead of simply serializing the data exposed by
the public properties. Furthermore, it needed to support the reverse operation
and deserialize DataSets from DiffGrams as well.
The following example serializes a DataSet loaded from a simple
XML document. Note that we do not set up anything different from the way we
serialized objects throughout the past two chapters to enable serialization to
the DiffGram format.
18
Listing 10.14
Serializing a DataSet containing simple contacts file
<?xml version="1.0" encoding="utf-8" ?>
<contacts>
<contact>
<name>Roger Dolph</name>
<address>100
Washington Ave, Atlanta, GA</address>
<phone>123-4568</phone>
</contact>
</contacts>
static void SerializeContactDataSet()
{
DataSet dataset = new DataSet();
dataset.ReadXml("contacts.xml");
XmlSerializer ser = new
XmlSerializer( typeof( DataSet ) );
XmlTextWriter writer =
new XmlTextWriter( "dataset.xml",
System.Text.Encoding.UTF8 );
writer.Formatting =
Formatting.Indented;
ser.Serialize( writer,
dataset );
writer.Close();
}
When we examine the output of the XmlSerializer we find two
distinct sections. One is the DiffGram we expected to find. The other one is an
XML schema describing the data structure and the relationships inside the
DataSet in addition to the data in the various tables. The schema information
is necessary to accurately deserialize the DataSet later on, since the DiffGram
does not include relationship information. Listing 10.15 shows the complete
output of the method above.