C# Tutorial - XML Serialization

Skill

C# Tutorial - XML Serialization

Posted in:

A long while ago we posted a tutorial on how to serialize objects to a binary file. While this is very useful, unfortunately the resulting file is not very human readable. In this tutorial, I'm going to demonstrate how to serialize your own objects to and from an XML file.

Since .NET can use reflection to get property names, basic serialization is unbelievably simple. It only gets slightly difficult when you want to name your XML tags differently than your property names (but still not very hard). If you've ever used an XML serialization package in C++ like boost, tinyXML, or libXML2, you'll see how comparatively easy C# is to use.

Let's start with a basic example. Below is an object that stores some information about a movie.

public class Movie
{
  public string Title
  { get; set; }

  public int Rating
  { get; set; }

  public DateTime ReleaseDate
  { get; set; }
}

All right, now that we have an object, let's write a function that will save it to XML.

static public void SerializeToXML(Movie movie)
{
  XmlSerializer serializer = new XmlSerializer(typeof(Movie));
  TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
  serializer.Serialize(textWriter, movie);
  textWriter.Close();
}

The first thing I do is create an XMLSerializer (located in the System.Xml.Serialization namespace) that will serialize objects of type Movie. The XMLSerializer will serialize objects to a stream, so we'll have to create one of those next. In this case, I want to serialize it to a file, so I create a TextWriter. I then simply call Serialize on the XMLSerializer passing in the stream (textWriter) and the object (movie). Lastly I close the TextWriter because you should always close opened files. That's it! Let's create a movie object and see how this is used.

static void Main(string[] args)
{
  Movie movie = new Movie();
  movie.Title = "Starship Troopers";
  movie.ReleaseDate = DateTime.Parse("11/7/1997");
  movie.Rating = 6.9f;

  SerializeToXML(movie);
}

static public void SerializeToXML(Movie movie)
{
  XmlSerializer serializer = new XmlSerializer(typeof(Movie));
  TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
  serializer.Serialize(textWriter, movie);
  textWriter.Close();
}

After this code executes, we'll have an XML file with the contents of our movie object.

<?xml version="1.0" encoding="utf-8"?>
<Movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>Starship Troopers</Title>
  <Rating>6.9</Rating>
  <ReleaseDate>1997-11-07T00:00:00</ReleaseDate>
</Movie>

If you noticed, all of the XML tag names are the same as the property names. If we want to change those, we can simply add an attribute above each property that sets the tag name.

public class Movie
{
  [XmlElement("MovieName")]
  public string Title
  { get; set; }

  [XmlElement("MovieRating")]
  public float Rating
  { get; set; }

  [XmlElement("MovieReleaseDate")]
  public DateTime ReleaseDate
  { get; set; }
}

Now when the same code is executed again, we get our custom tag names.

<?xml version="1.0" encoding="utf-8"?>
<Movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MovieName>Starship Troopers</MovieName>
  <MovieRating>6.9</MovieRating>
  <MovieReleaseDate>1997-11-07T00:00:00</MovieReleaseDate>
</Movie>

Sometimes, in XML, you want information stored as an attribute of another tag instead of a tag by itself. This can be easily accomplished with another property attribute.

public class Movie
{
  [XmlAttribute("MovieName")]
  public string Title
  { get; set; }

  [XmlElement("MovieRating")]
  public float Rating
  { get; set; }

  [XmlElement("MovieReleaseDate")]
  public DateTime ReleaseDate
  { get; set; }
}

With this code, MovieName will now be an attribute on the Movie tag.

<?xml version="1.0" encoding="utf-8"?>
<Movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   MovieName="Starship Troopers">
  <MovieRating>6.9</MovieRating>
  <MovieReleaseDate>1997-11-07T00:00:00</MovieReleaseDate>
</Movie>

Let's move on to something a little more interesting. Let's create another movie and serialize a List of them to our XML file. Here's the modified code to do just that:

static void Main(string[] args)
{
  Movie movie = new Movie();
  movie.Title = "Starship Troopers";
  movie.ReleaseDate = DateTime.Parse("11/7/1997");
  movie.Rating = 6.9f;

  Movie movie2 = new Movie();
  movie2.Title = "Ace Ventura: When Nature Calls";
  movie2.ReleaseDate = DateTime.Parse("11/10/1995");
  movie2.Rating = 5.4f;

  List<Movie> movies = new List<Movie>() { movie, movie2 };

  SerializeToXML(movies);
}

static public void SerializeToXML(List<Movie> movies)
{
  XmlSerializer serializer = new XmlSerializer(typeof(List<Movie>));
  TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
  serializer.Serialize(textWriter, movies);
  textWriter.Close();
}

Now we have XML that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Movie MovieName="Starship Troopers">
    <MovieRating>6.9</MovieRating>
    <MovieReleaseDate>1997-11-07T00:00:00</MovieReleaseDate>
  </Movie>
  <Movie MovieName="Ace Ventura: When Nature Calls">
    <MovieRating>5.4</MovieRating>
    <MovieReleaseDate>1995-11-10T00:00:00</MovieReleaseDate>
  </Movie>
</ArrayOfMovie>

Ok, so you can see how easy it is to get your objects into an XML document. Let's now look at how to read an XML document back into our objects - deserialization. The process of deserializing is very similar to what we did for serialization.

static List<Movie> DeserializeFromXML()
{
   XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
   TextReader textReader = new StreamReader(@"C:\movie.xml");
   List<Movie> movies;
   movies = (List<Movie>)deserializer.Deserialize(textReader);
   textReader.Close();

   return movies;
}

Just like before, we first create an XmlSerializer that can deserialize objects of type List<Movie>. The XmlSerializer also deserializes from a stream, so we create a file stream from our XML file. We then simply call Deserialize on the stream and cast the output to our desired type. Now the movies List is populated with objects that we previously serialized to the XML file.

The deserializer is very good at handling missing pieces of information in your XML file. Let's say the second movie didn't have the MovieName attribute on the Movie tag. When the XML file is deserialized, it simply populates that field with null. If MovieRating wasn't there, you'd receive 0. Since a DateTime object can't be null, if MovieReleaseDate was missing, you'd receive DateTime.MinValue (1/1/0001 12:00:00AM).

If the XML document contains invalid syntax, like say the first opening Movie tag was missing, the Deserialize call will fail with an InvalidOperationException. It will also be kind enough to specify the location in the file where it encountered the error (line number, column number).

One thing to remember is that the basic XML serialization won't maintain references. Let's say I populated my movies list with the same movie reference multiple times:

Movie movie = new Movie();
movie.Title = "Starship Troopers";
movie.ReleaseDate = DateTime.Parse("11/7/1997");
movie.Rating = 6.9f;

List<Movie> movies = new List<Movie>() { movie, movie };

Now I have a list containing two of the exact same movie reference. When I serialize and deserialize this list, it will be converted to two separate instances of the movie object - they would just have the same information. Along this same line, the XMLSerializer also doesn't support circular references. If you need this kind of flexibility, you should consider binary serialization.

There's still a lot to cover when it comes to XML serialization, but I think this tutorial covers enough of the basics to get things rolling. If you've got questions or anything else to say, leave us a comment.

John Wang
06/22/2008 - 07:59

Thank you very much!
Very clear.

reply

Bill Sorensen
06/22/2008 - 20:01

TextWriter implements IDisposable; this code would be safer if it used the using statement.

reply

The Reddest
06/23/2008 - 15:00

You're absolutely right. I'll modify the code examples to use the 'using' statement. That also would eliminate the need for the Close() call since the TextWriter closes itself when it's disposed.

reply

Yudy
06/23/2008 - 03:39

I am doubt that it is possible deserilize the XML file without doing the serilize object? That means if I have a XML file created manually and then I just want to get the object information in the project(read only), is it possible? And how?

reply

The Reddest
06/23/2008 - 15:05

The deserializer does not need XML that was created by the serializer. You can use any manually created XML document, just as long as the elements have matching property names.

reply

Yudy
06/24/2008 - 00:52

Thank you very much.
As you said if the elements match the property names, I can deserialize the XML document. So this means I cannot use the deserializer in .NET like XmlSerializer.Deserializer()? Can you give me an example to clarify it?

reply

The Reddest
06/24/2008 - 09:07

Let's say I have a hand written XML document like this:

<?xml version="1.0"?>
<MyObject>
  <MyPropertyA>10</MyPropertyA>
  <MyPropertyB>20</MyPropertyB>
</MyObject>

And I have a C# object like this:

public class MyObject
{
  public int MyPropertyA {get; set;}
  public int MyPropertyB {get; set;}
}

I can deserialize that XML document into my object using the following code:

XmlSerializer deserializer =
  new XmlSerializer(typeof(MyObject));
TextReader textReader = new StreamReader(@"C:\myXMLDoc.xml");
MyObject myObj =
  (MyObject)deserializer.Deserialize(textReader);
textReader.Close();

Since the XML document has the correct root node and has tags that match property names of my object, everything will work fine. If I changed the root node of my XML document to something like this:

<?xml version="1.0"?>
<SomeOtherObject>
  <MyPropertyA>10</MyPropertyA>
  <MyPropertyB>20</MyPropertyB>
</SomeOtherObject>

the deserialization won't work, because it will expect the root node to be named "MyObject". However, you can still make this work by modifying the object to include what the root node is supposed to be named:

[XmlRoot("SomeOtherObject")]
public class MyObject
{
  public int MyPropertyA {get; set;}
  public int MyPropertyB {get; set;}
}

Now we're saying that even though the object is named "MyObject", it will be called "SomeOtherObject" inside the XML document. And again, everything will work.

Hope this clears stuff up.

reply

Tony
07/14/2008 - 04:53

Well..
And if i want

6,9
07-11-1997

??
(Custom DateTime and Flot number format)..

reply

Anise
07/16/2008 - 09:00

This explanation has been very helpful and is nice and clear, thanks!

However, a complete code listing at the bottom with all the usings included, and where the code blocks should be placed in either a single file or in Visual Studio, would be even more helpful to us newbies.

reply

K03123
07/18/2008 - 01:42

thanks for the great article.

in your example above, if i want to set attribute for element name lets say Rating, how can i do that? or do i have to create Rating as Class and apply attribute there? i think i can do that way but creating new class just to fulfill that doesn't seem quite right.

any suggestion?

cheers

reply

Ramki
07/30/2008 - 12:04

Can I do deserialize and deserialize specific node not entrie XML doc?
for example I want to deserialzie only data in below xml file. Can it be done?

20

20

reply

The Reddest
07/30/2008 - 16:57

Sorry Ramki, but the comment system strips < and >. Refer to this post on how to put xml and other code in the comments.

reply

Syed Farabi
09/04/2008 - 22:42

This is a great tutorial I found.

Thanks a lot to provide this kind of clear tutorial.

reply

Anonymous
09/08/2008 - 00:08

dear sir
Request you to solve my issue.i.e. Let me know how to use jquery inside a xml file.if iam using so its giving err0r as
1.$ is not defined
2.script is not defined

reply

Andrew
09/16/2008 - 03:45

Is there any way to serialize an object that has private or internal set accessors, e.g:

public propertyname {private set; get; }

I can't seem to get it to work.

reply

Anonymous
07/21/2009 - 12:20

Strangley, serializing a VB class that has readonly properties works if you impliment ISerializable and use reflection to skip over your readonly properties, but it doesn't seem to play ball in c#.

reply

Hagit
11/30/2008 - 03:51

Thank for the important article.
i'm trying to do serilization with files that are writing to an isolate storage - without success. do you have an idea why??

reply

Brandon
12/08/2008 - 14:34

Extremely helpful, Reddest. Always love your blog for the best and most useful information - keep up the good work!

reply

Jon
12/11/2008 - 16:51

Excellent tutorial! I look forward to reading more.

reply

Kazi Sabbir Ibna Ataur
12/13/2008 - 02:09

Saved lot of my time.Easy to follow. Keep this great works coming.

reply

Rotem or
12/16/2008 - 03:19

im trying to do almost the same thing eccapt from that i want to store the stream in a string on a hidden field on the page
but it seems that the deserialization dosnt work if i put it on a string
(if ichange the source to a file it works like charm)
any idieas ?

reply

Deo
01/01/2009 - 00:29

Thanks a lot. good article to beign with. tried the examples and really good.

reply

Adnene
03/05/2009 - 11:05

Thanks a lot for the example
I want to ask you how to serialize a complex object, I mean an object with some generic list property type. I have always an invalid operation exception or error when creating the xml document or a reflection error.

structure sample:

object1
prop1 string
prop2 int
prop3 List

object2
prop1 string
prop2 string
prop3 List

reply

The Reddest
03/05/2009 - 11:33

Lists have XML serialization support built right in. The XML serializer doesn't support circular references, so if the List in object1::prop3 contains a reference to object1, you'll get an error. That's all I've got for now. If you post some example code, I can probably help more.

reply

Ben
01/21/2010 - 06:18

Maybe xml serialization doesn't work on mixed type lists. I think it may only work on typed lists, like List.

reply

Janak
03/16/2009 - 01:42

Nice article. But i'm stuck on one issue where i want to write comment in between the node. How can i achieve that using serialization?

For e.g. I want the output like:

<?xml version="1.0"?>
<SomeOtherObject>
   <!-- #if (condition) -->
  <MyPropertyA>10</MyPropertyA>
  <!-- #endif -->
  <MyPropertyB>20</MyPropertyB>
</SomeOtherObject>

reply

Sal
03/27/2009 - 13:39

This was fantastic information, thank you. Now I have another question. What if what the document I want to read from XML has the following structure in one of its subtrees? how should I create the object?

<NameValuePairs>
    <Name>Alpha</Name>
    <Value>1.7</Value>
    <Name>Beta</Name>
    <Value>0.3</Value>
    <Name>OtherName</Name>
    <Value>OtherValue</Value>
    <Name>ManyOtherNamesCouldFollow</Name>
    <Value>WithTheirRespectiveValues</Value>
</NameValuePairs>

Would using a list or even a Dictionary work?

Thanks in advance.

reply

geo_c
08/04/2009 - 04:34

that xml does not conform to a relational model and is not recommended for serialization.
in your xml, the name & value elements are required to have a particular order of existence, otherise the value of one may get mixed up with some other name.

in xml standards, design like this creates ambiguity and hard to use for programming APIs.

reply

Anonymous
11/03/2009 - 12:14

Good information, thank you for commenting. I've had a similar instance where I wanted to added different elements, but definitely wanted to remove the ambiguity. As it turns out, I modified my XML to use attributes to absorb the names/values.

And thanks for the suggestion about the XmlArray. I'm looking to utilize that suggestion in a project.

reply

Anonymous
06/25/2009 - 08:36

How would you serialize and deserialize this?

<PropertyNames>
  <Name># Plate</Name>                                     
  <Name>G Plate</Name>                                 
  <Name>C Plate</Name>                                 
  <Name>1 Head</Name>                                  
  <Name>2 Heads</Name>                                 
  <Name>3 Heads</Name>         
</PropertyNames>

reply

The Reddest
06/25/2009 - 11:34

I don't think deserialization can handle this case by default. You can override the XML serializer for an object, however I don't know the syntax off the top of my head.

reply

geo_c
08/04/2009 - 04:35

XmlArray attribute could be utilized.

reply

sweeny
10/29/2009 - 07:10

Thanks for the simple explanation of serialization

reply

Z.K.
12/28/2009 - 01:08

Nice article, but I have one question.

I understand everything up to the point where you write the List to the xml file. I understand how to create a List and how to add elements to the List and even how to write the List to the xml file. Your example though shows a root element of ArrayOfMovie and then Movie elements inside that. I cannot see how you create the ArrayOfMovie. When I do it, I get a bunch of Movie elements and an error about more than one root element. I have looked over the code several times, but I do not see how you did that. Could you explain in more detail or provide a file that I could download to look at?

reply

stanbeard
02/01/2010 - 01:58

Great article!

If I have:

public class Movie {
    string Name;
    Actor LeadActor;
}

public class Actor {
    string Name;
    DateTime DOB;
}

And I want to serialize the Movie like this:

<Movie>
    <Name>Casino Royale</Name>
    <LeadActor>Daniel Craig</LeadActor>
</Movie>

How do I do that? That is, how do I tell the Movie class to only serialize the Name property of the LeadActor member instead of the whole object?

Thanks!

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors