Serialize/deserialize your objects using generics. Customize settings like indentation, encoding, namespaces and others.
Table of contents
- Xml Serialization overview
- A generic serializer class – XmlSerializer<T>
- The scenario – User Shopping Cart
- Using the code
- Using the XmlSerializer settings
- Example 1: Remove XML indentation
- Example 2: Remove namespaces
- Example 3: Add custom namespaces
- Example 4: Specify encoding
- Example 5: Remove XML declaration
- Example 6: File serialization
XML Serialization Overview
XML serialization is the process of converting an object into a XML string in order to persist it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
Some good uses for XML serialization/deserialization are [1]:
- 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
A generic serializer class – XmlSerializer<T>
I’ve created a generic class to serialize/deserialize XML:
This class allows us to:
- Serialize an object to a XML string
- Deserialize an object from a XML string
- Serialize an object to a XML file
- Deserialize an object from a XML file
It’s also possible to customize some settings like indentation, encoding, namespaces and others (see examples below).