CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

David Hayden [MVP C#]

         .NET Tutorials, Patterns, and Practices

XML Serialization - Conversion of XML Documents and Streams to Common Language Runtime Objects and Vice Versa

I want to discuss a simple solution for accessing global application settings from your web pages using ASP.NET page inheritance and XML files as a storage medium for your settings.  Before I can do that, however, I need to discuss XML serialization and deserialization as a method of persisting and fetching application settings from XML.

XML Serialization Defined

The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa.

 

XML serialization essentially allows us to convert objects in our applications into an XML representation that we can send over the "wire", persist to a file, etc. Later on we can use a process, called deserialization, to convert the XML back into the object if we so desire.  There are some gotchas about how you need to set up your objects, how deeply XML serialization will "copy" your objects, etc., but that is out of the scope of this article.

The following code below shows an example of serializing the object siteSettings to a file.  First, we create a new SiteSettings object that we are going to serialize to a file.  We then create a new XMLSerializer object and pass it the type of the object we are going to serialize.  And last, we open up a new stream and write the XML to our configuration file.  You can see the code and output below.

 

XML Serialization
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[XmlType(Namespace="urn:davidhayden-com:config")]
[XmlRoot(Namespace="urn:davidhayden-com:config")]
public class SiteSettings
{
    #region Private Members
    
    private string _name;
    private string _url;
    private string _emailAddress;
    
    #endregion
    
    #region Properties

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    
    public string Url
    {
        get { return _url; }
        set { _url = value; }
    }
    
    public string EmailAddress
    {
        get { return _emailAddress; }
        set { _emailAddress = value; }
    }
    
    #endregion

    public static SiteSettings Fetch()
    {
        SiteSettings siteSettings;
        
        XmlSerializer serializer = new XmlSerializer(typeof(SiteSettings));

        using (StreamReader reader = new StreamReader("sitesettings.config"))
        {
            siteSettings = serializer.Deserialize(reader) as SiteSettings;
        }

        return siteSettings;

    }
}

public class TestClass
{
    public static void Main()
    {
        SiteSettings siteSettings = new SiteSettings();
        siteSettings.Name = "DavidHayden.com";
        siteSettings.Url = "http://www.davidhayden.com/";
        siteSettings.EmailAddress = "nospam@nospam.com";
        
        XmlSerializer serializer = new XmlSerializer(typeof(SiteSettings));
        
        using (StreamWriter writer = new StreamWriter("sitesettings.config"))
        {
            serializer.Serialize(writer, siteSettings);
        }
    }
}

 

Output of XML Serialization: sitesettings.config
<?xml version="1.0" encoding="utf-8"?>
<SiteSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="urn:davidhayden-com:config">
  <Name>DavidHayden.com</Name>
  <Url>http://www.davidhayden.com/</Url>
  <EmailAddress>nospam@nospam.com</EmailAddress>
</SiteSettings>

 

So now we have serialized the contents of the object into a file and we need to get it back. As you can tell in the SiteSettings Class above, I already have a static Fetch() method that converts the XML back into an object.  Below is the Fetch() method repeated.  Nothing exciting here, except for how easy it is.  We are essentially doing the exact opposite - reading the xml from the file and calling Deserialize to re-create the siteSettings object.

 

Converting the XML back to SiteSettings (deserialization)
public static SiteSettings Fetch()
{
    SiteSettings siteSettings;
    
    XmlSerializer serializer = new XmlSerializer(typeof(SiteSettings));

    using (StreamReader reader = new StreamReader("sitesettings.config"))
    {
        siteSettings = serializer.Deserialize(reader) as SiteSettings;
    }

    return siteSettings;

}

 

Here is some code you can run in Snippet Compiler that will allow you to see it happen:

 

Deserialization in Action
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[XmlType(Namespace="urn:davidhayden-com:config")]
[XmlRoot(Namespace="urn:davidhayden-com:config")]
public class SiteSettings
{
    #region Private Members
    
    private string _name;
    private string _url;
    private string _emailAddress;
    
    #endregion
    
    #region Properties

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    
    public string Url
    {
        get { return _url; }
        set { _url = value; }
    }
    
    public string EmailAddress
    {
        get { return _emailAddress; }
        set { _emailAddress = value; }
    }
    
    #endregion

    public static SiteSettings Fetch()
    {
        SiteSettings siteSettings;
        
        XmlSerializer serializer = new XmlSerializer(typeof(SiteSettings));

        using (StreamReader reader = new StreamReader("sitesettings.config"))
        {
            siteSettings = serializer.Deserialize(reader) as SiteSettings;
        }

        return siteSettings;

    }
}

public class MyClass
{
    public static void Main()
    {
        // DeSerialize
        SiteSettings mySettings = SiteSettings.Fetch();
        Console.WriteLine("Name = {0}", mySettings.Name);
        Console.WriteLine("Url = {0}", mySettings.Url);
        Console.WriteLine("Email Address = {0}", mySettings.EmailAddress);
        Console.ReadLine();
    }
}

 

It is probably quite obvious how to use this now in your base pages for retrieving global application settings for your ASP.NET pages, but I will toss up a code example in my next post in case it might not be so clear.


Published Mar 01 2005, 06:13 AM by David Hayden
Filed under:

Comments

TrackBack said:

# March 1, 2005 8:07 AM

TrackBack said:

# March 1, 2005 8:10 AM

TrackBack said:

Blog tools for Alt. IDE's setup and some JS Native Object Expansion
# March 1, 2005 8:19 AM

TrackBack said:

# March 1, 2005 3:13 PM

TrackBack said:

# March 1, 2005 4:10 PM

Eric Wise said:

Now here is something I'd been thinking about playing with for quite some time but never got around to doing it. Great post David!
# March 1, 2005 6:47 PM

TrackBack said:

# March 2, 2005 9:55 AM

TrackBack said:

# March 2, 2005 10:31 AM

TrackBack said:

# March 3, 2005 5:44 PM

Anand Kakde said:

Simple yet effective post David. Thank you.

Can we take a step further about how to set up the objects (Dos and Don’ts) effectively based on your following comment:
{There are some gotchas about how you need to set up your objects, how deeply XML serialization will "copy" your objects, etc., but that is out of the scope of this article.}
# March 10, 2005 10:47 AM

David Hayden said:

For the sake of this example, you just need to make sure you have a public read/write property for each private field so that all your settings get serialized and that you have a default public constructor (which c# implicity created for me in this case but I recommend explicity creating one).

As far as a more advanced article on XML Serialization, I hadn't planned on writing anything in the near future. You can probably Google for some advanced articles in the meantime.
# March 11, 2005 10:56 AM

TrackBack said:

# March 14, 2005 12:02 PM

TrackBack said:

# March 14, 2005 12:09 PM
Check out Devlicio.us!

This Blog

Syndication

News

CodeBetter.Com Home