On The Insider: Michael Jackson In Wheelchair

Implement XML serialization in the .NET Framework

Tags: .NET, Zach Smith, Microsoft .NET Framework, XML Serialization, XML

  • Save
  • Print
  • Digg This
  • 3

Takeaway: From remoting to Web services, serialization plays an integral part in many modern software architectures. Zach Smith explains how XML Serialization works and shows how to take advantage of the .NET Framework's built-in serialization functions with the included sample application.

This article is also available as a TechRepublic download, which includes an example application and sample code.

Serialization is the act of saving an object to a storage medium or transforming the object so that it may be sent across a network. After an object is serialized, you will want to deserialize it which is the act of turning the data back into a usable object. This type of functionality is used anytime an object must be marshaled from one context to another, for example when an object crosses App Domains. Another example is a Web service --Objects are serialized at the server, sent over the network (marshaled) to the client, and then deserialized into usable objects.

From binary to XML, the .NET Framework provides developers with many serialization options, and even allows developers to create their own serialization routines. In this article, I will concentrate on XML serialization and show you how you can take advantage of this built-in functionality.

XML serialization

One form of serialization provided by the .NET Framework is XML Serialization. In this type of serialization the object state is saved in XML format. This allows the serialized object to be accessed and modified by different systems, even systems that are not written in .NET. Another advantage is that the serialized object is human readable and writable -- updating the object is as simple as opening it with notepad and changing its values.

XML Serialization is often used in remoting and Web Service projects, although you may find it in other areas such as DataSet marshalling. When combined with XPath queries and Predicate methods, XML Serialization can be used to implement an object oriented database -- something I will write about in future articles.

Using XML serialization

It is relatively easy to take advantage of the built in XML Serialization methods in the .NET Framework. There are just a couple classes and attributes that you need to be familiar with to start working with simple XML Serialization:

  • System.Xml.Serialization namespace: Contains the classes and functionality needed to work with XML Serialization. This namespace should be included in a "using" directive at the top of classes which will work with XML Serialization.
  • XmlSerializer class: Provides functionality for serializing and deserializing objects.
  • XmlIgnore attribute: Instructs the XmlSerializer class to skip over members that you do not want serialized.

This list simply gets you started. There are many more objects that you can use when working with XML Serialization.

A simple example of serializing a Customer object is shown in Listing A. This Customer object is defined in the sample application included in the download.

Listing A


    Customer customer = newCustomer();
    customer.FirstName = "Zach";
    customer.LastName = "Smith";

    XmlSerializer serializer = newXmlSerializer(typeof(Customer));

    StringWriter writer = newStringWriter();
    serializer.Serialize(writer, customer);

    Console.WriteLine(writer.ToString());

As you can see, XML serialization is a straight-forward process. We simply create the object we need serialized, create the XmlSerializer for that type of object, and call XmlSerializer.Serialize. The serialized object is then written to the provided Stream – in this case a StringWriter named "writer".

If you look at the serialized object you will notice that it is easily readable. The following is what the serialized Customer object looks like:

<?xml version="1.0" encoding="utf-16"?>
<Customer xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Orders />
  <LastName>Smith</LastName>
  <FirstName>Zach</FirstName>
</Customer>

Here you see that the properties of the Customer object are serialized, including the Orders property, which is a List of Order objects. If you compare this output to the definition of the Customer class you will notice that the "Income" property is not listed. That is because the Income property has an XmlIgnore attribute applied to it which makes the XML serialization library skip the property during serialization. A side effect of skipping the property during serialization is that the property will not be deserialized, and will always contain its default value upon deserialization.

The Orders node is empty because this customer contained no orders. If, however, we serialize a Customer object that contains orders, we will have output similar to this:

<?xml version="1.0" encoding="utf-16"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Orders>
    <Order>
      <Total>34.56</Total>
    </Order>
    <Order>
      <Total>156.56</Total>
    </Order>
  </Orders>
  <LastName>Smith</LastName>
  <FirstName>Zach</FirstName>
</Customer>

Notice that each order object is serialized individually and placed in the Orders node of the serialized Customer object. If you were to deserialize this Customer object, the associated Order objects would be deserialized as well.

Note: Each object which is to be serialized or deserialized must have an empty default constructor. If the object does not implement an empty constructor an exception will be thrown.

Deserializing objects

Deserializing objects is just as easy as serializing them. The following code (Listing B) demonstrates how to deserialize an object that is held in a file:

Listing B


    XmlSerializer serializer = new XmlSerializer(typeof(Customer));

    FileStream file = File.OpenRead(fileToWrite);

    Customer customer = (Customer)serializer.Deserialize(file);

    file.Close();

The only differences in this code and the serialization code is that here we call XmlSerializer.Deserialize. This method returns an object, which we then must cast into the type of object we will be working with.

Other uses

In some instances it is useful to implement XML Serialization to store and retrieve setting files. For instance, instead of writing a custom XML parsing routine to pick up and parse a setting file, you could just create a class that contains the needed properties and serialize it to disk. This would allow manual editing of the file if needed, and would save you from writing any custom XML parsing code. This same type of methodology could be applied to any type of information an application may need to store from one execution to the next.

As I mentioned earlier, it is feasible that you could create an object oriented database by using XML serialization in conjunction with Predicate methods (compiled searches), XPath (ad-hoc searches), and the XmlDocument (provider) object. I have been working on this project and will cover the implementation and ideas behind it in future articles. The goal is to have a simple object oriented database completely implemented in under 200 lines of C# code.

Use XML serialization to your advantage

Now that you are familiar with XML serialization, I hope you can find uses for it in your projects. Personally, I could have saved a lot of time by using XML serialization for complex application settings, not to mention a few other modules of my applications. Hopefully this article will help keep you from making the same mistakes I did!

  • Save
  • Print
  • Digg This
  • 3

Print/View all Posts Comments on this article

What do you think of the .NET Framework?Mark W. Kaelin Techrepublic | 12/14/06
I am a fanpuneet@...  | 12/28/06
I'm fast becoming oneTony Hopkinson  | 12/28/06
Fan of Framewokitsnikihere42@...  | 12/28/06

What do you think?

Article Categories

Security
Security Solutions, IT Locksmith
Networking and Communications
E-mail Administration NetNote, Cisco Routers and Switches
CIO and IT Management
Project Management, CIO Issues, Strategies that Scale
Desktops, Laptops & OS
Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
Data Management
Oracle, SQL Server
Servers
Windows NT, Linux NetNote, Windows Server 2003
Career Development
Geek Trivia
Software/Web Development
Web Development Zone, Visual Basic, .NET

Cracking Open

advertisement
Click Here