#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">類型</param>
/// <param name="obj">對象</param>
/// <returns></returns>
public string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");//把命名空間設置為空,這樣就沒有命名空間了
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化對象
xml.Serialize(Stream, obj,ns);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
public static string ObjectToXmlSerializer(Object Obj) { XmlWriterSettings settings = new XmlWriterSettings(); //去除xml聲明 settings.OmitXmlDeclaration = true; settings.Encoding = Encoding.Default; System.IO.MemoryStream mem = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(mem, settings)) { //去除默認命名空間xmlns:xsd和xmlns:xsi XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer formatter = new XmlSerializer(Obj.GetType()); formatter.Serialize(writer, Obj, ns); } return Encoding.Default.GetString(mem.ToArray()); }
源網址:http://www.cnblogs.com/kissdodog/archive/2013/12/10/3468385.html