首先,封装一个XML序列化和反序列化的函数。
引入程序集
1 using System.Xml.Serialization; 2 using System.IO;
1 public class XmlSerialize 2 { 3 /// <summary> 4 /// 反序列化XML为类实例 5 /// </summary> 6 /// <typeparam name="T"></typeparam> 7 /// <param name="xmlObj"></param> 8 /// <returns></returns> 9 public static T DeserializeXML<T>(string xmlObj) 10 { 11 XmlSerializer serializer = new XmlSerializer(typeof(T)); 12 using (StringReader reader = new StringReader(xmlObj)) 13 { 14 return (T)serializer.Deserialize(reader); 15 } 16 } 17 18 /// <summary> 19 /// 序列化类实例为XML 20 /// </summary> 21 /// <typeparam name="T"></typeparam> 22 /// <param name="obj"></param> 23 /// <returns></returns> 24 public static string SerializeXML<T>(T obj) 25 { 26 using (StringWriter writer = new StringWriter()) 27 { 28 new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj); 29 return writer.ToString(); 30 } 31 } 32 }
再建一个实体类,添加序列化标记
1 [Serializable] 2 public class UserInfo 3 { 4 public string Name; 5 6 public string sex; 7 }
序列化一下
1 UserInfo user = new UserInfo(); 2 user.Name = "bdstjk"; 3 user.sex = "男"; 4 String strXml = XmlSerialize.SerializeXML<UserInfo>(user); 5 Console.WriteLine(strXml);
序列化结果
反序列化
1 string strXml = "<?xml version="1.0" encoding="utf-16"?><UserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Name>bdstjk</Name><sex>男</sex></UserInfo>"; 2 UserInfo user = XmlSerialize.DeserializeXML<UserInfo>(strXml); 3 Console.WriteLine(user.Name);
一个新方法
1 public static string Serialize<T>(this T obj, bool omitXmlDeclaration = false) 2 { 3 XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 4 ns.Add("", ""); //Xmlns去除 5 var sb = new StringBuilder(); 6 using (var xw = XmlWriter.Create(sb, new XmlWriterSettings() 7 { 8 OmitXmlDeclaration = omitXmlDeclaration, 9 ConformanceLevel = ConformanceLevel.Auto, 10 Indent = true 11 })) 12 { 13 var xs = new XmlSerializer(obj.GetType()); 14 xs.Serialize(xw, obj,ns); 15 } 16 return sb.ToString(); 17 }
调用时 omitXmlDeclaration 为 true 时 ,XML头消失
转自 http://www.cnblogs.com/bdstjk/archive/2012/01/19/2519860.html