Friday, March 7, 2014

XML Serialization: Making the call generic.

I've been experimenting with XML serialization quite a bit lately. It's working really well, consuming my xml calls. In the code example below.


public PlayerStatistic LoadPlayerStats(string xmlString)
{
    PlayerStatistic xmlToLoad = new PlayerStatistic();
    if (string.IsNullOrEmpty(xmlString) == false)
    {
        // convert string to stream
        byte[] byteArray = Encoding.UTF8.GetBytes(xmlString);
        MemoryStream stream = new MemoryStream(byteArray);

        // load into a streamreader and then deserialize
        StreamReader streamReader = new StreamReader(stream);
        XmlSerializer reader = new XmlSerializer(typeof(PlayerStatistic));
        return (PlayerStatistic)reader.Deserialize(streamReader);
    }
    else
    {
        return null;
    }
}


This is great, but as I needed to deserialize other documents, I found myself writing the same code, over and over. Enter Generics. I can write a generic version that I can pass the datatype into.

public T LoadXML<T>(string xmlString)
{
    if (string.IsNullOrEmpty(xmlString) == false)
    {
        // convert string to stream
        byte[] byteArray = Encoding.UTF8.GetBytes(xmlString);
        MemoryStream stream = new MemoryStream(byteArray);

        // load into a streamreader and then deserialize
        StreamReader streamReader = new StreamReader(stream);
        XmlSerializer reader = new XmlSerializer(typeof(T));
        return (T)reader.Deserialize(streamReader);
    }
    else
    {
        return default(T);
    }
}


To call this, using the example above, it's as simple as:

PlayerStatistic LoadXML<RawPlayerAchievementsForApp.PlayerStatistic>(rawXMLString);

No comments:

Post a Comment