C# XmlSerializer类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static class XmlSerializer<T>
{
public static string Serialize(T o)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream())
{
xmlSerializer.Serialize(stream, o);
return Encoding.ASCII.GetString(stream.ToArray());
}
}
public static T DeSerialize(string xmlString)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(xmlString)))
{
return (T)xmlSerializer.Deserialize(stream);
}
}
public static string Serialize(T obj, string xsdNs, string xsiNs)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsd", xsdNs);
ns.Add("xsi", xsiNs);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
StringBuilder sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, obj, ns);
return sb.Replace("utf-16", "utf-8").ToString();
}
}
public static T DeSerialize(ref string xmlText)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlText))
{
return (T)serializer.Deserialize(reader);
}
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static byte[] SoapSerialize(object obj)
{
MemoryStream stream = new MemoryStream();
new SoapFormatter().Serialize(stream, obj);
stream.SetLength(stream.Position);
return stream.ToArray();
}
public static object SoapDeserialize(byte[] data)
{
MemoryStream stream = new MemoryStream();
stream.Write(data, 0, data.Length);
stream.Position = 0L;
return new SoapFormatter().Deserialize(stream);
}