3

I need to store some objects as XML files in order to save data and load it later. I coded this and it works for me:

public static Project Load(String file)
{
    using (var stream = System.IO.File.OpenRead(file))
    {
        var serializer = new XmlSerializer(typeof(Project));
        return serializer.Deserialize(stream) as Project;
    }
}

public static void Save(Project p, String file)
{
    using (var writer = new System.IO.StreamWriter(file))
    {
        var serializer = new XmlSerializer(p.GetType());
        serializer.Serialize(writer, p);
        writer.Flush();
    }
}

Now, I need to do this with other kind of objects and I don't really want to copy/paste these methods for every object class.

Is possible to pass the object class to methods and make these methods generic for any object class?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
zaroca
  • 33
  • 3
  • Note that `writer.Flush()` is completely pointless in your sample as it will happen due to disposing writer with `using` anyway. – Alexei Levenkov Nov 14 '14 at 16:24
  • Thanks Alexei for the link (it seems very useful for this kind of situations) and for the tip about writer.Flush() :) – zaroca Nov 14 '14 at 16:31

1 Answers1

5

i usually use this both methods from https://stackoverflow.com/a/271423/1315444 hope this helps :D

/// <summary>Serializes an object of type T in to an xml string</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="obj">Object to serialize</param>
/// <returns>A string that represents Xml, empty otherwise</returns>
public static string XmlSerialize<T>(this T obj) where T : class, new()
{
    if (obj == null) throw new ArgumentNullException("obj");      
    var serializer = new XmlSerializer(typeof(T));
    using (var writer = new StringWriter())
    {
        serializer.Serialize(writer, obj);
        return writer.ToString();
    }
}


/// <summary>Deserializes an xml string in to an object of Type T</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="xml">Xml as string to deserialize from</param>
/// <returns>A new object of type T is successful, null if failed</returns>
public static T XmlDeserialize<T>(this string xml) where T : class, new()
{
    if (xml == null) throw new ArgumentNullException("xml");    
    var serializer = new XmlSerializer(typeof(T));
    using (var reader = new StringReader(xml))
    {
        try { return (T)serializer.Deserialize(reader); }
        catch { return null; } // Could not be deserialized to this type.
    }
}

then you can go with

Project p = new Project();
string result = p.XmlSerialize();
Project p2 = result.XmlDeserialize<Project>();
Community
  • 1
  • 1
fubo
  • 44,811
  • 17
  • 103
  • 137