C# Generic Convert XML to Object

Rédigé par Sozezzo - - Aucun commentaire

Easy way to convert a generic objet to xml string and xml string to generic object.

public static string Serialize<t>(T xml);

public static void Deserialize<t>(ref T obj, string xml);

/// <summary>
/// Deserialize xml --> obj
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="xml"></param>
public static void Deserialize<T>(ref T obj, string xml)
{
   var serializer
     = new System.Xml.Serialization.XmlSerializer(typeof(T));
   using (var reader = new System.IO.StringReader(xml))
   {
       obj = (T)serializer.Deserialize(reader);
   }
}

/// <summary>
/// Serialize obj --> xml
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static string Serialize<T>(T xml)
{

  System.IO.MemoryStream stIDoc = new System.IO.MemoryStream();
  System.Xml.Serialization.XmlSerializer sr
     = new System.Xml.Serialization.XmlSerializer(typeof(T));
  sr.Serialize(stIDoc, xml);
  System.Data.SqlTypes.SqlXml r
     = new System.Data.SqlTypes.SqlXml(stIDoc);
  return r.Value;
}

Les commentaires sont fermés.