XML序列化反序列化
using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace ConsoleApp.Test { public class XmlTest { public void TestXml() { var dept = new Depts { Id = 1, Name = "部门", UserList = new List<Users> { new Users { Id=2, CreateTime=DateTime.Now.ToString("yyyy-MM-dd"), IsLock=true, Name="张三", Sex="男" }, new Users { Id=2, CreateTime=DateTime.Now.ToString("yyyy-MM-dd"), IsLock=false, Name="李四", Sex="女" } } }; var xmlStr = XmlSerializer(dept); var xmlObj = XmlDeserialize(typeof(Depts),xmlStr); Console.WriteLine(xmlStr); } /// <summary> /// 序列化XML /// </summary> /// <param name="obj">对象</param> /// <returns></returns> public static string XmlSerializer(object obj) { var str = string.Empty; using (var stream=new MemoryStream()) { //创建序列化对象 XmlSerializer xml = new XmlSerializer(obj.GetType()); //序列化对象 xml.Serialize(stream, obj); stream.Position = 0; using (var sr = new StreamReader(stream)) { str = sr.ReadToEnd(); } } return str; } public static string Serializer1(object obj,string encoding="utf-8",bool utf8Bom=false) { string rtStr; using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); //要求缩进 settings.Indent = false; //注意如果不设置encoding默认将输出utf-16 //注意这儿不能直接用Encoding.UTF8如果用Encoding.UTF8将在输出文本的最前面添加4个字节的非xml内容 settings.Encoding = encoding == "utf-8"?new UTF8Encoding(utf8Bom): Encoding.GetEncoding(encoding); //设置换行符 settings.NewLineChars = string.Empty;//Environment.NewLine; using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings)) { XmlSerializerNamespaces xsn = new XmlSerializerNamespaces(); xsn.Add(string.Empty, string.Empty); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(xmlWriter, obj, xsn); } rtStr = Encoding.GetEncoding(encoding).GetString(ms.ToArray()); } return rtStr; } /// <summary> /// 反序列化XML /// </summary> /// <param name="type">对象类型</param> /// <param name="xmlStr">xml字符串</param> /// <returns></returns> public object XmlDeserialize(Type type,string xmlStr) { using (StringReader rdr = new StringReader(xmlStr)) { //声明序列化对象实例serializer XmlSerializer serializer = new XmlSerializer(type); //反序列化,并将反序列化结果值赋给变量i return serializer.Deserialize(rdr); } } } [XmlRoot("dept")] public class Depts { public int Id { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlArray("users"), XmlArrayItem("user")]//定义数组节点名称和子集名称 public List<Users> UserList{get;set;} } [XmlRoot("user")] public class Users { public int Id { get; set; } public string Name { get; set; } [XmlIgnore]//要求不序列化Sex属性 public string Sex { get; set; } [XmlAttribute("islock")] //定义islock属性的序列化为user节点的属性 public bool IsLock { get; set; } [XmlElement("createdate")]//设置createdate属性序列化为user子元素 public string CreateTime { get; set; } } }