Binary and XML Serialization - XML Serialization
(Page 4 of 4 )
XML serialization converts the public fields and properties of an object into an XML stream that conforms to a specific XML Schema. XML serialization does not include type information, unlike binary serialization, which does. For example, if I have an employee object that belongs to a Company namespace, there is no guarantee that it is deserialized into an object of the same type.
The class that needs to be serialized using XML serialization will be tagged with the[Serializable]attribute (in the same way as with binary serialization):
[Serializable]
public class Book
{...}
In this case, however, a classmusthave a default constructor to be serialized by the XML Serializer. Here is the class declaration:
[Serializable]
public class Book
{
private string isbn;
public string ISBN
{
get { return isbn; }
set { isbn = value; }
}
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private string author;
public string Author
{
get { return author; }
set { author = value; }
}
public Book()
{
isbn = "";
title = "";
author = "";
}
public Book(string isbn, string title, string author)
{
this.isbn = isbn;
this.title = title;
this.author = author;
}
public override string ToString()
{
return string.Format("ISBN: {0}, Title: {1}, Author: {2}",
isbn, title, author);
}
To serialize the book object into an XML file, we need theXmlSerializerclass and theStreamWriterclass:
XmlSerializer serializer = new XmlSerializer(typeof(Book));
StreamWriter writer = new StreamWriter("Book.xml");
TheXmlSerializerclass expects the type of object being serialized (Bookin this case). With theStreamWriterconstructor, you specify the name of the XML file where the object will be serialized. Note in this case that we did not specify a path; the file will be created in the Debug folder within the Bin folder. Other than that, theSerializeBook()andDeserializeBook()methods are similar to those of the binary formatter:
private static void SerializeBook(Book favoriteBook)
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
StreamWriter writer = new StreamWriter("Book.xml");
serializer.Serialize(writer, favoriteBook);
writer.Close();
}
private static Book DeserializeBook()
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
FileStream fStream = new FileStream("Book.xml",FileMode.Open);
Book b = (Book)serializer.Deserialize(fStream);
fStream.Close();
return b;
}
Now that we have the methods, we can call them from withinMain() after creating aBookobject:
static void Main(string[] args)
{
Book favoriteBook = new Book("0-7356-2527-1",
"Programming with ASP.NET 3.5", "Dino Esposito");
Console.WriteLine("Serializing Book...");
SerializeBook(favoriteBook);
Console.WriteLine("Book serialized");
Console.WriteLine("Deserializing Book...");
Book myBook = DeserializeBook();
Console.WriteLine(myBook); //calling ToString()
Console.ReadLine();
}
After running the application, the content of Book.xml will be as follows:
<?xml version="1.0" encoding="utf-8" ?>
- <Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ISBN>0-7356-2527-1</ISBN>
<Title>Programming with ASP.NET 3.5</Title>
<Author>Dino Esposito</Author>
</Book>
If you look carefully at the XML file, you notice that the tags start with upper case letters, which means that they represent the properties, not the fields. This illustrates the fact that when using XML serialization, only the public elements of the class are serialized (not the private ones).
Conclusion
The.NET framework provides very powerful and flexible serialization classes. Two important categories are binary serialization and XML serialization. Use binary serialization when working within the boundaries of .NET applications. XML serialization is very handy when serialized objects are used by non-.NET applications. Another key distinction is that binary serialization serializes public and private members, while XML serialization only serializes public members.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |