/// <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;
}
}
}
转载于:https://www.cnblogs.com/songconglai/p/11353016.html