Click here to Skip to main content
Click here to Skip to main content

XML Serialization in .NET

By , 26 Jul 2002
 

Sample Image

Introduction

My previous article, Hash Table and Serialization in .NET, describes how the content of a hash table is serialized to and deserialized from a binary file. This article continues the serialization topic, and describes XML serialization in .NET, where objects are serialized and deserialized into and from XML documents.

XML serialization implemented by XMLSerializer class converts an object's public classes, properties and fields to a serial XML format. The following example shows how an object of the Person class is serialized into a XML document.

class Person
{
   public Person( string firstName, string lastName )
   {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public string firstName;
   public string lastName;
}   

static void Main()
{
   Person person = new Person( "John", "Doe" );

   XmlSerializer x = new XmlSerializer( typeof(Person) );
   TextWriter writer = new StreamWriter( "person.xml" );
   x.Serialize( writer, person );
}

If you run the above example, you will get a runtime error mesage, System.InvalidOperationException. The error is caused by the line XmlSerializer x = new XmlSerializer( typeof(Person) );. As it turns out the class Person requires a modifier public and a default constructor. These are common mistakes that I made while working with XmlSerializer class. After you add the public modifier and the default constructor to the Person class, you will get the following XML elements.

<?xml version="1.0 encoding="utf-8"?>
<Person xmlns:xsd="http:www.w3.org/2001/XMLScheme"
        xmlns:xsi="http:www.w3.org/2001/XMLScheme-instance">
    <firstName>John</firstName>
    <lastName>Doe</lastName>
</Person>

As you can see, the element names in the above XML document reflect the public member variable names. You may ask what if I want to make the member variables private. Can I still serialize this class?. XmlSerializer cannot serialize private members, however, you can use public properties as the access methods to the private members as shown below.

   public string FirstName
   {
      get { return firstName; }
      set { firstName = value; }
   }

   public string LastName
   {
      get { return lastName; }
      set { lastName = value; }
   }

   private string firstName;
   private string lastName;

In this case, the XML elements would be FirstName and LastName instead of firstname and lastname respectively to reflect the property names. You can change the XML element names, so that they are different from the property names by using C# attributes. For example, if you want to change the FirstName element to MyFirstName, you can add the following XML element attribute to the FirstName property.

[XmlElement(ElementName = "MyFirstName")]
public string FirstName
{
   get { return firstName; }
   set { firstName = value; }
}

Now, let's expand on the above concept to a more complex application such as a phone book application as described in my previous article, Hash Table and Serialization in .NET. The following UML class diagram shows the relationships between classes that are part of the application. The Contacts class contains one or more Contact, and Contact class contains a Person class and a PhoneNumber class.

UML Diagram

The Person, PhoneNumber, and Contact classes are straight forward and self explanatory, so I will not go into details of these classes. The Contacts class has a private hash table member variable table that takes the Person object as the key and the Contact object as the value. Since this hash table member variable contains all of the contacts, it will be nice if it can be serialized directly to a XML document. However, as it turns out, XmlSerializer does not work with the Hashtable class because the Hashtable indexer takes a non-integer parameter (object parameter), and XmlSerializer expects indexers with only an integer parameter. So in order to serialize all of the contacts to the XML document, the hash table is converted to a Contact array, and this array is then serialized to a XML document as shown below.

// Create an instance of Contact array, and copy the content of 
// the hash table to this array
Contact[] aContact = new Contact[table.Count];
table.Values.CopyTo( aContact, 0 );

// Deserialize the content of the Contact array to a XML file
XmlSerializer x = new XmlSerializer( typeof(Contact[]) );
TextWriter writer = new StreamWriter( "phonebook.xml" );
x.Serialize( writer, aContact );

To deserialize the XML elements from the XML document to the hash table, the above steps will be reversed. The XML elements are first deserialize to a Contact array, and then each member of the array is added to the hash table as follows.

// Create an instance of the XmlSerializer class of type Contact array 
XmlSerializer x = new XmlSerializer( typeof(Contact[]) );

// Read the XML file if it exists ---
FileStream fs = null;
try
{
   fs = new FileStream( "phonebook.xml", FileMode.Open );

   // Deserialize the content of the XML file to a Contact array 
   // utilizing XMLReader
   XmlReader reader = new XmlTextReader(fs);         
   Contact[] contacts = (Contact[]) x.Deserialize( reader );

   // Add each member of the Contact array to the hash table
   for ( int i = 0; i < contacts.Length; i++ )
   {
      Contact contact = (Contact) contacts[i];
      table.Add( contact.GetPerson, contact );
   }
}
catch( FileNotFoundException )
{
   // Do nothing if the file does not exists
}
finally
{
   if ( fs != null ) fs.Close();
}

That is all for now. I hope you enjoy this brief introduction on XML serialization in .NET.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Liong Ng
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to Serialize [CDATA] node using XMLSerializermemberghorpade.sangram11 Dec '07 - 2:21 
<Hi,
I can able to add the CDATA section inside the xml string but when i go to serialize it, it is converting the opening "<" to < which does not understand by the server as
for C++ (Xerces)and java(jaxb) doing it correctly.
 
The request string with CDATA before serializing is as

<body><bodystring><![CDATA[<xml version="1.0" encoding="utf-8">GroupMember]]></bodystring></body>
 
The request String after passing to XMLSerializer is as follows, which change the CDATA node tag which leads to DOM parsing exception.
 
<body><bodystring><![CDATA[<?xml version="1.0" encoding="utf-8"?><InitTypeByNamesInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://abc.com/Schemas/Internal/Core/2006-03/Types"><typeNames>GroupMember</typeNames></InitTypeByNamesInput>]]></bodystring></body>

 
Can anybody help me how i can preserve the <![CDATA] node as it is so that my server can understand the request?
 

Thanks in advance.
Sangram.]]></bodystring></body>
Questionserializing a System.Windows.Forms.Button Classmemberankur.ag198124 Jul '06 - 21:32 
QuestionAny plans to upgrade to 2.0?memberwws3580111 Feb '06 - 19:15 
Generalcommentsmemberadras17 Jan '06 - 21:56 
GeneralXML Serialization in which a variable name can be assigned to ElementNamememberSnehal Ganjigatti22 Jul '05 - 10:15 
GeneralDouble array serializedmemberExnor1 Jun '05 - 3:05 
Generaldeserializationmembersomiali9 Oct '03 - 7:15 
GeneralSerializing XmlSchema Arraymembermanij28 Jul '03 - 4:49 
GeneralSerializing Objects within objectsmemberJustin Armstrong30 Jun '03 - 9:47 
GeneralRe: Serializing Objects within objectseditorHeath Stewart30 Jun '03 - 11:15 
GeneralRe: Serializing Objects within objectsmemberJustin Armstrong2 Jul '03 - 13:25 
GeneralRe: Serializing Objects within objectseditorHeath Stewart2 Jul '03 - 18:06 
GeneralRe: Serializing Objects within objectsmemberJustin Armstrong3 Jul '03 - 6:49 
GeneralRe: Serializing Objects within objectseditorHeath Stewart3 Jul '03 - 8:47 
GeneralRe: Serializing Objects within objectsmemberJustin Armstrong3 Jul '03 - 10:39 
GeneralRe: Serializing Objects within objectseditorHeath Stewart3 Jul '03 - 10:59 
GeneralRe: Serializing Objects within objectsmemberJustin Armstrong4 Jul '03 - 8:03 
GeneralRe: Serializing Objects within objectseditorHeath Stewart7 Jul '03 - 2:15 
GeneralRe: Serializing Objects within objectsmemberJustin Armstrong8 Jul '03 - 6:40 
GeneralRTF stringmemberlerede22 Jun '03 - 21:09 
GeneralSerializing ArrayList of ArrayListsmemberAaron R>18 Jun '03 - 6:55 
GeneralRe: Serializing ArrayList of ArrayListsmemberLiong28 Jun '03 - 11:25 
Generalhelp with serializationmemberbaby.chai26 Mar '03 - 8:46 
GeneralRe: help with serializationmemberLiong2 Apr '03 - 5:28 
GeneralRe: help with serializationmemberbannistj18 Nov '03 - 4:20 
QuestionHow to serialize non primitive properties?memberleppie28 Jul '02 - 9:11 
AnswerRe: How to serialize non primitive properties?membercschmidt30 Jul '02 - 7:03 
GeneralRe: How to serialize non primitive properties?memberleppie30 Jul '02 - 12:19 
AnswerRe: How to serialize non primitive properties?memberLiong1 Aug '02 - 11:24 
AnswerRe: How to serialize non primitive properties?memberomoshima9 Apr '03 - 11:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 27 Jul 2002
Article Copyright 2002 by Liong Ng
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid