c# 實體類轉XML

/// <summary>
/// 將實體類轉換成XML
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string XmlSerialize<T>(T obj)
{
//using (StringWriter sw = new StringWriter())
//{
// Type t = obj.GetType();
// var serializer = new XmlSerializer(obj.GetType(),"");
// serializer.Serialize(sw, obj);
// sw.Close();
// string serialized = sw.ToString();
// serialized = serialized.Replace(@" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""", "");
// serialized = serialized.Replace(@" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""", "");
// return serialized;
//}
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.IndentChars = "";
settings.NewLineChars = "";
//settings.NewLineChars = "\r\n";
settings.Encoding = Encoding.UTF8;
settings.OmitXmlDeclaration = true; // 不生成聲明頭
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(sw, settings))
{
// 強制指定命名空間,覆蓋默認的命名空間
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(xmlWriter, obj, namespaces);
xmlWriter.Close();
string serialized = sw.ToString();
return serialized;
}
}

}spa

相關文章
相關標籤/搜索