SoFunction
Updated on 2025-03-07

C# method to implement Xml serialization and deserialization

#region Deserialization
/// <summary>
/// Deserialization
/// </summary>
/// <param name="xml">XML string</param>
/// <returns></returns>
public static T Deserialize<T>(string xml)
{
    return (T)Deserialize(typeof(T), xml);
}
/// <summary>
/// Deserialization
/// </summary>
/// <param name="stream">Byte Stream</param>
/// <returns></returns>
public static T Deserialize<T>(Stream stream)
{
    return (T)Deserialize(typeof(T), stream);
}
/// <summary>
/// Deserialization
/// </summary>
/// <param name="type">type</param>
/// <param name="xml">XML string</param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
    try
    {
 xml = ("\r\n", "").Replace("\0", "").Trim();
 using (StringReader sr = new StringReader(xml))
 {
     XmlSerializer xmldes = new XmlSerializer(type);
     return (sr);
 }
    }
    catch (Exception e)
    {
 return null;
    }
}
/// <summary>
/// Deserialization
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
    XmlSerializer xmldes = new XmlSerializer(type);
    return (stream);
}
#endregion
#region Serialization
/// <summary>
/// Serialization
/// </summary>
/// <param name="obj">Object</param>
/// <returns></returns>
public static string Serializer<T>(T obj)
{
    return Serializer(typeof(T), obj);
}
/// <summary>
/// Serialization
/// </summary>
/// <param name="type">type</param>
/// <param name="obj">Object</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
    MemoryStream Stream = new MemoryStream();
    XmlSerializerNamespaces _name = new XmlSerializerNamespaces();
_name.Add("", "");//In this way, remove xmlns:xsi and xmlns:xsd in attribute
    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
= new UTF8Encoding(false);//Set encoding, Encoding.UTF8 cannot be used, which will result in BOM tags
= true;//Set automatic indentation
// = true;//Delete XmlDeclaration: <?xml version="1.0" encoding="utf-16"?>
    // = "\r\n";
    // = ;
    XmlSerializer xml = new XmlSerializer(type);
    try
    {
 using (XmlWriter xmlWriter = (Stream, xmlWriterSettings))
 {
//Serialize the object
     (xmlWriter, obj, _name);
 }
    }
    catch (InvalidOperationException)
    {
 throw;
    }
    return Encoding.(()).Trim();
}
#endregion
}