On a recent project we needed to read data from a file. We couldn't simply de-serialize using the built in .net serialization as the file format had already been defined and we didn't have the time to write custom serialization. So our problem was that given an xml file format such as the one below, how best to consume it?

<Products>
<Product name="Name1" manufacturer="Manufacturer1"/>
<Product  name="Name2" manufacturer=""Manufacturer2"/>
</Products>

This had been solved in a few places by using an xml parser. I didn't like this as it seemed fragile.

Auto generate classes

After some thought I realised we could create the classes from the xml using the xml schema definition tool. First create an xml schema from the visual studio command prompt using xsd.exe;

xsd.exe products.xml

Then we create the classes from the schema;

xsd.exe /classes products.xsd

Deserialize files into objects

We now have the classes required to de-serialize the file into .net objects.  The below code and utility class can now handle the de-serialization;

[Test]
public void Should_load_products()
{
     var p = new XmlEntityReader<Products>();
     var productList = p.Read("blog\productdata.xml");

     productList.Items.Length.ShouldBe(2);
}

public class XmlEntityReader<T> where T : class
{
    public T Read(string storeFullPath)
    {
       return Read(new FileStream(storeFullPath, FileMode.Open));
    }

    public T Read(Stream storeStream)
    {
        storeStream.Position = 0;
        T settings;
        var serializer = new XmlSerializer(typeof(T));
        using (TextReader tr = new StreamReader(storeStream))
        {
           settings = serializer.Deserialize(tr) as T;
           tr.Close();
        }
        return settings;
    }
}