18

When using XML serialization in C#, I use code like this:

public MyObject LoadData()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        return (MyObject)xmlSerializer.Deserialize(reader);
    }
}

(and similar code for deserialization).

It requires casting and is not really nice. Is there a way, directly in .NET Framework, to use generics with serialization? That is to say to write something like:

public MyObject LoadData()
{
    // Generics here.
    XmlSerializer<MyObject> xmlSerializer = new XmlSerializer();
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        // No casts nevermore.
        return xmlSerializer.Deserialize(reader);
    }
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
  • A generic `XmlSerializer` as shown in your example above does not exist. You will need to create your own wrapper if you desire thsi functionality. – Steve Guidi Apr 19 '10 at 19:31
  • Necromancy, but I had to respond to the above comment: Of course it doesn't exist, that's why the question was asked. If it existed, the example would work as-is. – EKW Mar 15 '18 at 18:38

5 Answers5

30

An addition to @Oded, you can make the method Generic aswell:

public T ConvertXml<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(new StringReader(xml));
}

This way you don't need to make the whole class generic and you can use it like this:

var result = ConvertXml<MyObject>(source);
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
  • 2
    Accepting this answer, rather than Oded one, because this one does not require class, and in fact, most of the time, I don't want to create one (for example when, in a small project, all XML data is accessed from one class). Thanks to everyone for answering. – Arseni Mourzenko Apr 19 '10 at 20:51
  • Why was this answer accepted? It contains a code error (semicolon in using) and XmlSerializer class is not IDisposable, therefore cannot be used in a using scope, so it won't compile for two reasons... – Koen Jul 13 '10 at 09:49
  • 2
    @Koen, sorry missed that, thanks for the heads up. Corrected it. – Filip Ekberg Jul 13 '10 at 20:20
  • Any idea how this might be used with an assembly generator like http://xgenplus.codeplex.com/ or MS SGen http://msdn.microsoft.com/en-us/library/bk3w6240(vs.80).aspx – Lucas B May 31 '12 at 15:52
13

Make your serialization class/method generic:

public T LoadData<T>()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        return (T)xmlSerializer.Deserialize(reader);
    }
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

A simple generic wrapper:

public class GenericSerializer<T> : XmlSerializer
{
    public GenericSerializer(): base(typeof(T)) { }
}

This will serialize your object to the bin/debug folder:

static void Main(string[] args)
{
   Person p = new Person { Name = "HelloWorld" };
   GenericSerializer<Person> ser = new GenericSerializer<Person>();
   ser.Serialize(new StreamWriter("person.xml"), p);
}
neo112
  • 1,703
  • 2
  • 17
  • 39
2

Try this.

public class SerializeConfig<T> where T : class
{
    public static void Serialize(string path, T type)
    {
        var serializer = new XmlSerializer(type.GetType());
        using (var writer = new FileStream(path, FileMode.Create))
        {
            serializer.Serialize(writer, type);
        }
    }

    public static T DeSerialize(string path)
    {
        T type;
        var serializer = new XmlSerializer(typeof(T));
        using (var reader = XmlReader.Create(path))
        {
            type = serializer.Deserialize(reader) as T;
        }
        return type;
    }
}
Hasan Javaid
  • 111
  • 1
  • 4
0

always work's for me

  public static string ObjectToXmlSerialize<T>(T dataToSerialize)
    {
        try
        {
            var stringwriter = new System.IO.StringWriter();
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
        catch (Exception ex)
        {
        }
        return null;
    }

and this is for Deserialize:

  public static T XmlDeserializeToObject<T>(string xmlText)
    {
        try
        {
            var stringReader = new System.IO.StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
        }
        return default(T);
    }
tokenaizer
  • 208
  • 1
  • 5
  • 17