c# xml序列化类的代码实例详解
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Imps.Services.CommonV4;
namespace Imps.Services.IDCService.Utility
{
public class XMLSerializerEx
{
private static ITracing _tracing = TracingManager.GetTracing("XMLSerializerEx");
///
/// 对象转换成XML
///
///
///
///
public static string SaveXmlFromObj(T obj)
{
if (obj == null) return null;
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
MemoryStream stream = new MemoryStream();
XmlTextWriter xtw = new XmlTextWriter(stream, Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
try
{
serializer.Serialize(stream, obj,namespaces);
}
catch { return null; }
stream.Position = 0;
string returnStr = string.Empty;
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
returnStr += line;
}
}
return returnStr;
}
public static T LoadObjFromXML(Stream s)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
try
{
return ((T)serializer.Deserialize(s));
}
catch { return default(T); }
}
///
/// XML反序列化到对象
///
///
///
///
public static T LoadObjFromXML(string data)
{
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(stream, Encoding.UTF8))
{
sw.Write(data);
sw.Flush();
stream.Seek(0, SeekOrigin.Begin);
return LoadObjFromXML(stream);
}
}
}
}
} 以上就是c# xml序列化类的代码实例详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!










