XML Serialization in .NET

The Dehydration Process

"Okay, okay, I get the picture," you may be muttering now, "but how do I do it?" I'm going to walk you through a simple example of serializing an object to be saved to disk as an XML file. Keep in mind that in .NET we can serialize objects into a binary format or SOAP format as well as into XML, but we will focus solely on XML for this article for the sake of brevity. Also, the object in the example is obviously very simplistic and wouldn't be practical in the real world, but it will serve as a means to clearly illustrate how to serialize an object. The same principles used in this example can then be applied to more complicated tasks. Note that all the code used for this example is available for download at the end of this article; also a live demo is available).

First of all, let's take a look at the class that is the blueprint for our object (this snippet can be found in the file, xmlser.aspx).

<XMLRoot(ElementName:="Class_Person")> _
public class Person
private m_sName as string
private m_iAge as integer
<XMLElement(ElementName:="Property_Name")> _
public property Name() as string
    get
    return m_sName
    end get
    set(byval sNewName as string)
    m_sName = sNewName
    end set
end property
<XMLElement(ElementName:="Property_Age")> _
public property Age() as integer
    get
    return m_iAge
    end get
    set(byval iNewAge as integer)
    m_iAge = iNewAge
    end set
end property
public function Hello() as string
    dim s as string
    s = "Hi! My name is " & Name & " and I am " & Age & " years old."
    return s
end function
public function Goodbye() as string
    return "So long!"
end function
end class

This looks pretty similar to the class we saw earlier but with a few adjustments. First of all, notice the lines that say, <XMLRoot... and <XMLElement... These are .NET attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place. The next difference you will notice is that there are two methods declared in the class called, Hello() and Goodbye(). These really have no bearing on the serialization that will take place, but we will use them later to demonstrate the state of the object at a given point in the serialization process.

Next let's look at the code that actually instantiates the object and then serializes it.

dim oXS as XMLSerializer = new XMLSerializer(GetType(Person))
dim oLucky as new Person()
dim oStmW as StreamWriter
'Set properties
oLucky.Name = "Lucky Day"
oLucky.Age = 52
'Display property values
Response.Write("Hello() = " & oLucky.Hello() & "<br />")
Response.Write("Goodbye() = " & oLucky.Goodbye() & "<br />")
'Serialize object to XML and write it to XML file
oStmW = new StreamWriter(Server.MapPath("lucky.xml"))
oXS.Serialize(oStmW, oLucky)
oStmW.Close()

First of all, we declare and instantiate an XMLSerializer object. You'll notice that we had to tell it right from the onset, using the GetType() function, what type of object it's going to be serializing. Next you see that we assign values to the Name and Age properties of the Person object we instantiated. Then we output to the ASP.NET page what the properties are set to by calling the Hello() and Goodbye() methods of the Person object. Remember that this is only so that we can see what's happening with the object during this process. Next comes the good stuff: We instantiate a StreamWriter object and tell it that it will be writing to a file called, lucky.xml. We then call the Serialize() method of the XMLSerializer object and send it our Person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter, thereby closing the file.

That's it. If everything works correctly, an XML file (lucky.xml) will be written to disk. It should look like this:

<?xml version="1.0" encoding="utf-8"?>
<Class_Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Property_Age>52</Property_Age>
<Property_Name>Lucky Day</Property_Name>
</Class_Person>

Notice that the names of the XML elements are exactly as we specified in the <XMLRoot()> and <XMLElement()> attributes in the class earlier. Next, we'll examine how to "rehydrate" our XML into an object instance.

You might also like...

Comments

About the author

Anthony Hart United States

Anthony Hart has been working in IT since 1995. Currently, he is managing Oneirasoft, LLC, a consulting and software business. In his free time (if there is such a thing) he enjoys composing mus...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Never trust a programmer in a suit.” - Anonymous