I like XML. I like it a lot. For most smaller applications a database – even SQLite and the likes – is complete overkill. Still, you have to save your application data somewhere. Enter XML.

I also like to access my application data in a typesafe manner and I don’t like to reinvent the wheel (or in this case, the XML serialization). Enter System.Xml.Serialization.

The idea is simple and straight forward. You create a class with some properties, you decorate the properties with some attributes, combine the whole thing with the System.Xml.Serialization.XmlSerializer and presto chango: you’ve got yourself some simple and effective XML serialization. Allow me to demonstrate:

// XML serializable class
[XmlRoot("myRootNode")]
public class TestRoot
{
  [XmlAttribute("myAttribute")]
  public int MyAttribute { get; set; }

  [XmlElement("myElement")]
  public string MyElement { get; set; }
}

Now you create a new TestRoot object, set the properties and serialize it as follows.

// XML serializable class
XmlSerializer serializer = new XmlSerializer(typeof(TestRoot));
using (StreamWriter writer = File.CreateText("test.xml"))
{
  serializer.Serialize(writer, this);
}

This will result in an XML file similar to this:

<myRootNode myAttribute="42">
  <myElement>my element text</myElement>
</myRootNode>

You can also create more complicated structures, you just need the right attributes. If you want to have an object with an array (unfortunately arrays are the only collections that are allowed) of child elements, there are two different ways of doing this.

Method 1:

// XML serializable class
[XmlRoot("myRootNode")]
public class TestRoot
{
  [XmlArray("myArray")]
  [XmlArrayItem("myItem")]
  public string[] MyItems { get; set; }
}
<myRootNode>
  <myArray>
    <myItem>my item text 1</myItem>
    <myItem>my item text 2</myItem>
    <myItem>my item text 3</myItem>
  </myArray>
</myRootNode>

Method 2:

// XML serializable class
[XmlRoot("myRootNode")]
public class TestRoot
{
  [XmlElement("myItem")]
  public string[] MyItems { get; set; }
}
<myRootNode>
  <myItem>my item text 1</myItem>
  <myItem>my item text 2</myItem>
  <myItem>my item text 3</myItem>
</myRootNode>

The sky’s the limit. All this also works for complex elements. See the MSDN documentation for more information.

Leave a Reply

Your email address will not be published.

*