Library tutorials & articles

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.

Comments

  1. 09 Aug 2007 at 15:58

    Fantastic Article!!

    Thank you so much for writing that article.  That was the first clearly stated explanation on serialization that I have come across and it helped me tremendously!

    Kudos to you my friend!

    Jason Z

  2. 28 Jul 2006 at 11:52

    I have two text boxes in my .aspx form. At the click of a button I need to generate an xml with the following schema.

    <?xml version="1.0" encoding="utf-16"?>
    <ns0:Root xmlns:ns0="http://Demo123.Schm_In">
      <No_1>      Contents of textBox 1       </No_1>
      <No_2>      Contents of textBox 2       </No_2>
    </ns0:Root>



    Now i need to post this through hppt.

    Pls give me the code in C#

  3. 14 Jan 2005 at 08:33
    What does this have to do with raisins? I see no raisins.
  4. 14 Jul 2003 at 11:28

    A good article for XML in .NET. This technology will truely standardize things, its a must for developers to learn and understand this.

  5. 01 Jan 1999 at 00:00

    This thread is for discussions of XML Serialization in .NET.

Leave a comment

Sign in or Join us (it's free).

Anthony Hart 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 music ...
AddThis

Related discussion

Related podcasts

  • Episode 10: LINQ

    K Scott leads us in a discussion of LINQ, including: What is it How introducing LINQ to .NET changed the framework LINQ Providers LINQ to XML LINQ to SQL - how it's different from EF, tips and tricks, when to use it Links: LINQpad 3rd Party LIN...

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

We'd love to hear what you think! Submit ideas or give us feedback