By

Typed lists in application configuration files

Being able to read .NET config files into typed classes has been around for ages!

So why am I writing about it? Good question! smile

An aspect of this which hasn’t been well covered is when we have a list of configuration items we want to load. We’ll use this app.config as an illustration:

  <Players type="Unit.Tests.XmlSerializerSectionHandler.Config.Players, Unit.Tests">

    <Player type="Unit.Tests.XmlSerializerSectionHandler.Config.Player, Unit.Tests">
      <FirstName>Homer</FirstName>
      <LastName>Simpson</LastName>
      <SupportsTeam>Leeds United</SupportsTeam>
    </Player>

    <Player type="Unit.Tests.XmlSerializerSectionHandler.Config.Player, Unit.Tests">
      <FirstName>Peter</FirstName>
      <LastName>Griffin</LastName>
      <SupportsTeam>Wales</SupportsTeam>
    </Player>

  </Players>

I won’t go over the full explanation of how to use the XmlSerializerSectionHandler typed class as Craig already does a great job.

Firstly we need some C# classes (other languages are available) to represent our XML. So in single form we have:

  public class Player {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string SupportsTeam { get; set; }
  }

So far, so uninteresting. The list form is thus:

  [XmlRoot("Players")]
  public class Players: List<Player> {

    public Players() {
      this.PlayerItems = new List<Player>();
    }

    [XmlElement("Player")]
    public List<Player> PlayerItems { get; set; }
  }

The XmlRoot declaration tells the framework this is the List version of the Player class. The PlayerItems is a container for the content of the XML. Finally ensure the PlayerItems object is created correctly in the constructor.

And that’s basically it. The full and unit tested version is up on github.

Hope this helps, until next time!

Posted in : techie-stuff, tips, development, development, configuration

Written by
Founder, Developer, tea maker