//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
      Basic Language Constructs
      Themes & Skins (web)
      Tips & Techniques
      XML Serialization
   Classic ASP 1.0
   Databases
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
asp.net2.aspfaq.com

ASP FAQ Tutorials :: ASP.NET 2.0 :: XML Serialization :: Simple Serialization


Simple Serialization

Overview

The .NET environment (particularly the 2.0 environment) is extraordinarily powerful.  This is particularly true when it comes to serialization.  Serialization and deserialization refers to the process of transforming an object in memory into another form, often using XML and a stream of some kind and then turning it back into an in memory object from a stream.

A Simple Example

Lets say we have the following class:

CSharp

public class Person
{
    public Person() { }
    public string Name;
    public string SSN;
}

VB


Public Class Person
    Public  Sub New()
    End Sub
    Public Name As String
    Public SSN As String
End Class

An object of this type could be represented by the following XML:

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>EJ Alexandra</Name>
  <SSN>123-45-6789</SSN>
</Person>

Actual Implementation Sample/Example

Luckily for us, .NET provides a class called XmlSerializer that will do this for us.  In fact, this suite of tools can serialize virtually any object and then de-serializer it afterwards.  This article will focus on a simple serializer/deserializer.  The following code will serialize a simple person object.

CSharp

// Create a person
Person p = new Person();
p.Name = "EJ Alexandra";
p.SSN = "123-45-6789";

// Create the xml serializer
XmlSerializer serializer = new XmlSerializer(p.GetType());

// Create a stream to write the XML to
StringWriter sw = new StringWriter();

// Serialize the object
serializer.Serialize(sw, p);

// Cose the stream
sw.Close();

// Save the XML as a string
string XML = sw.GetStringBuilder().ToString();

VB

' Create a person
Dim p As Person =  New Person() 
p.Name = "EJ Alexandra"
p.SSN = "123-45-6789"
 
' Create the xml serializer
Dim serializer As XmlSerializer =  New XmlSerializer(p.GetType()) 
 
' Create a stream to write the XML to
Dim sw As StringWriter =  New StringWriter() 
 
' Serialize the object
serializer.Serialize(sw, p)
 
' Cose the stream
sw.Close()
 
' Save the XML as a string
Dim XML As String =  sw.GetStringBuilder().ToString()

This XML can be transformed back into a Person object, using the following code:

CSharp

// Create a string reader to read the XML
StringReader sr = new StringReader(XML);

// De-serialize the person from the stream
Person personFromStream = (Person)serializer.Deserialize(sr);

VB

' Create a string reader to read the XML
Dim sr As StringReader =  New StringReader(XML) 
 
' De-serialize the person from the stream
Dim personFromStream As Person = CType(serializer.Deserialize(sr), Person)

Conclusion

Once an object has been serialized, it can be stored in a database, transmitted to distant sister-applications across the office or across the world.  This is an extremely powerful technology with a wide range of uses.

We will be providing more detailed articles on serializing objects over the next few weeks/months.

Complete File Source Code

default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
    </form>
</body>
</html>

default.aspx.cs/vb

CSharp

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Serialization;
using System.IO;

public class Person
{
    public Person() { }
    public string Name;
    public string SSN;
}

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a person
        Person p = new Person();
        p.Name = "EJ Alexandra";
        p.SSN = "123-45-6789";

        // Create the xml serializer
        XmlSerializer serializer = new XmlSerializer(p.GetType());

        // Create a stream to write the XML to
        StringWriter sw = new StringWriter();

        // Serialize the object
        serializer.Serialize(sw, p);

        // Cose the stream
        sw.Close();

        // Save the XML as a string
        string XML = sw.GetStringBuilder().ToString();

        // Show the XML on the page
        Label1.Text = String.Format("<h1>XML</h1><pre>{0}</pre>", 
                                     HttpUtility.HtmlEncode(XML));

        // Create a string reader to read the XML
        StringReader sr = new StringReader(XML);

        // De-serialize the person from the stream
        Person personFromStream = (Person)serializer.Deserialize(sr);

        Label1.Text += String.Format("<h1>From Xml</h1>Name: {0}", 
                                      personFromStream.Name);
    }
}

VB

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Xml.Serialization
Imports System.IO
 
Public Class Person
    Public  Sub New()
    End Sub
    Public Name As String
    Public SSN As String
End Class
 
Public partial Class _Default
     Inherits System.Web.UI.Page
    Protected  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Create a person
        Dim p As Person =  New Person() 
        p.Name = "EJ Alexandra"
        p.SSN = "123-45-6789"
 
        ' Create the xml serializer
        Dim serializer As XmlSerializer =  New XmlSerializer(p.GetType()) 
 
        ' Create a stream to write the XML to
        Dim sw As StringWriter =  New StringWriter() 
 
        ' Serialize the object
        serializer.Serialize(sw, p)
 
        ' Cose the stream
        sw.Close()
 
        ' Save the XML as a string
        Dim XML As String =  sw.GetStringBuilder().ToString() 
 
        ' Show the XML on the page
        Label1.Text = String.Format("<h1>XML</h1><pre>{0}</pre>", 
                                     HttpUtility.HtmlEncode(XML))
 
        ' Create a string reader to read the XML
        Dim sr As StringReader =  New StringReader(XML) 
 
        ' De-serialize the person from the stream
        Dim personFromStream As Person = CType(serializer.Deserialize(sr), Person)
 
        Label1.Text += String.Format("<h1>From Xml</h1>Name: {0}", 
                                      personFromStream.Name)
    End Sub
End Class

XML

<?xml version="1.0" encoding="utf-16"?> <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>EJ Alexandra</Name> <SSN>123-45-6789</SSN> </Person>

From Xml

Name: EJ Alexandra

'----------------------------------------------------------------
' Converted from C# to VB .NET using CSharpToVBConverter(1.2).
' Developed by: Kamal Patel (http://www.KamalPatel.net)
'----------------------------------------------------------------

 

 


Created: 6/7/2006 | Last Updated: 6/9/2006 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (612)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...