Working with Configuration Files – Quick Start

I’m currently working in a project where one need is to create easy customizable configuration files. The interest part comes when we need to read these configuration files and parsing them to .NET classes.

As I myself had to look up how some attributes work, I decided to share my experience creating those files, so this might help someone else going through the same problems.

To start off, let’s have a simple xml:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <host ip="127.0.01" port="80" username="test" password="pass" />
</main>

Now the our model class:

using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [XmlRoot("main")]
    public class ModelExampleConfiguration
    {
        [XmlElement("enabled")]
        public bool Enabled { get; set; }

        [XmlElement("name")]
        public string Name { get; set; }

        [XmlElement("host")]
        public HostConfiguration Host { get; set; }
    }

    public class HostConfiguration
    {
        [XmlAttribute("ip")]
        public string IP { get; set; }

        [XmlAttribute("port")]
        public int Port { get; set; }

        [XmlAttribute("username")]
        public string Username { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }
    }
}

Note: If you have your class and property names exactly like your config file then you don’t need to specify the attributes, but I just prefer to always use them, this way I can name my classes however I want.

Notice I’m handling both elements and attributes, using XmlElement and XmlAttributes.

Now, the code to parse the xml into a model class:

using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var reader = XmlReader.Create("Example.xml");

            var factory = new XmlSerializerFactory();
            var serializer = factory.CreateSerializer(typeof(ModelExampleConfiguration));
            var config = serializer.Deserialize(reader) as ModelExampleConfiguration;
        }
    }
}

// config.Enabled will output true
// config.Host.Username will output test

In the next post I’ll show how to deserialize a list / array of items.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s