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(); }
相关文章推荐
- C#实现对象XML序列化的方法
- C#对象XML序列化(一):序列化方法和常用特性
- C#对象XML序列化:序列化方法和常用特性
- C#对象XML序列化(一):序列化方法和常用特性
- 【C#】解决进行反序列化时出错:。InnerException 消息是“反序列化对象 属于类型 System.String 时出现错误。读取 XML 数据时,超出最大字符串内容长度配额 (8192)。
- C# WebApi Xml序列化问题解决方法:“ObjectContent`1”类型未能序列化内容类型“application/xml;charset=utf-8"的响应正文。...
- C#实现XML与实体类之间相互转换的方法(序列化与反序列化)
- C#对象的 Xml序列化与反序列化
- C#中对象,对象集合的简单Xml序列化与反序列化(已测试)
- C#温故而知新学习系列之XML编程—5-XmlSerializer类把对象序列化为XML文档
- c#中将对象序列化为xml(包括list)
- C#温故而知新学习系列之XML编程—8-XMLSerializer类把XML文档反序列化为对象
- C#中XML与对象之间的序列化、反序列化
- 分享一个对象序列化为XML和反序列化的扩展方法
- C# 对象XML序列化
- ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml) 用javascript在客户端删除某一个cookie键值对 input点击链接另一个页面,各种操作。 C# 往线程里传参数的方法总结 TCP/IP 协议 用C#+Selenium+ChromeDriver 生成我的咕咚跑步路线地图 (转)值得学习百度开源70+项目
- C#中的对象序列化成文本和XML案例
- C#温故而知新学习系列之XML编程—XmlSerializer类把对象序列化为XML文档(五)
- 类对象序列化(反序列化)成xml文件或者二进制文件到本地文件方法
- Jquery如何序列化form表单数据为JSON对象 C# ADO.NET中设置Like模糊查询的参数 从客户端出现小于等于公式符号引发检测到有潜在危险的Request.Form 值 jquery调用iframe里面的方法 Js根据Ip地址自动判断是哪个城市 【我们一起写框架】MVVM的WPF框架(三)—数据控件 设计模式之简单工厂模式(C#语言描述)