您的位置:首页 > 编程语言 > C#

c# 序列化对象为xml 方法

2018-05-04 19:05 405 查看

 

public static string XmlUtils(object obj, bool omitXmlDeclaration = true, bool indent = false,
bool useNameSpace = false)
{
var sb = new StringBuilder();
using (var xw = XmlWriter.Create(sb, new XmlWriterSettings()
{
OmitXmlDeclaration = omitXmlDeclaration, //是否省略xml声明
ConformanceLevel = ConformanceLevel.Auto,
Indent = indent //生成的xml是否缩进
}))
{
if (useNameSpace)
{
var xs = new XmlSerializer(obj.GetType());
xs.Serialize(xw, obj);
}
else
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty); //去除xml命名空间

var xs = new XmlSerializer(obj.GetType());
xs.Serialize(xw, obj, namespaces);
}
}

//...:nil=\"true\"表示该值为空
return sb.ToString();
}

 

 也可以做成扩展方法

public static string XmlUtils(this T obj, bool omitXmlDeclaration = true, bool indent = false,
bool useNameSpace = false)
{
var sb = new StringBuilder();
using (var xw = XmlWriter.Create(sb, new XmlWriterSettings()
{
OmitXmlDeclaration = omitXmlDeclaration, //是否省略xml声明
ConformanceLevel = ConformanceLevel.Auto,
Indent = indent //生成的xml是否缩进
}))
{
if (useNameSpace)
{
var xs = new XmlSerializer(obj.GetType());
xs.Serialize(xw, obj);
}
else
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty); //去除xml命名空间

var xs = new XmlSerializer(obj.GetType());
xs.Serialize(xw, obj, namespaces);
}
}

//...:nil=\"true\"表示该值为空
return sb.ToString();
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐