Home arrow ASP.NET arrow Page 2 - XML Serialization in ASP.NET

XML Serialization in ASP.NET

Ever wondered how you could save time and stress when dealing with session objects? Anthony will describe cleverly how this is done in XML using Object Serialisation.

Author Info:
By: Anthony Hart
Rating: 4 stars4 stars4 stars4 stars4 stars / 92
March 10, 2003
  1. · XML Serialization in ASP.NET
  2. · Part 1
  3. · Part 2
  4. · Conclusion

print this article

XML Serialization in ASP.NET - Part 1
(Page 2 of 4 )

Object Serialization

The technique to which I refer is called "Object Serialization". Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or a binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again. Let's look at an example to clarify this idea a little further. Suppose we have an object defined and instantiated as shown below:

Public Class Person
  private m_sName as string
  private m_iAge as integer
  public property Name() as string
      return m_sName
    end get
    set(byval sNewName as string)
      m_sName = sNewName
    end set
  end property
  public property Age() as integer
      return m_iAge
    end get
    set(byval iNewAge as integer)
      m_iAge = iNewAge
    end set
  end property
End Class

dim oPerson as New Person()
oPerson.Name = "Powdered Toast Man"
oPerson.Age = "38"

Let's say that for some reason, we wanted to save a copy of this object just as it is at this very moment. We could serialize it as an XML document that would look something like this:

 <Name>Powdered Toast Man</Name>

Then, at some later time when we needed to use the object again, we could just deserialize ("rehydrate") it and have our object restored to us just as it was at the moment we serialized it.

Why All This Dried Food?

"This serialization and deserialization is all well and good," you may be saying at this point, "but what can it be used for in real world web applications?" Very good question. What would be the sense of dehydrating a glass of milk just to rehydrate it and then dehydrate it again without drinking any? Never mind that it'll probably taste like the inside of your little brother's sock drawer (maybe I should have come up with a more tasty dehydrated food for this analogy). Some good uses for serialization/deserialization include:

  • Storing user preferences in an object.
  • Maintaining security information across pages and applications.
  • Modification of XML documents without using the DOM.
  • Passing an object from one application to another.
  • Passing an object from one domain to another.
  • Passing an object through a firewall as an XML string.
  • These are only a few of the many possibilities that serialization opens up for us.

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).

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
      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
      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)

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"
  <Property_Name>Lucky Day</Property_Name>

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

Next: Part 2 >>

blog comments powered by Disqus

- How Caching Means More Ca-ching, Part 2
- How Caching Means More Ca-ching, Part 1
- Reading a Delimited File Using ASP.Net and V...
- What is .Net and Where is ASP.NET?
- An Object Driven Interface with .Net
- Create Your Own Guestbook In ASP.NET
- HTTP File Download Without User Interaction ...
- Dynamically Using Methods in ASP.NET
- Changing the Page Size Interactively in a Da...
- XML Serialization in ASP.NET
- Using Objects in ASP.NET: Part 1/2
- IE Web Controls in VB.NET
- Class Frameworks in VB .NET
- Cryptographic Objects in C#: Part 1
- Sample Chapter: Pure ASP.Net

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials