在System.Xml.Serialization命名空间中提供了XML序列化类XmlSerializer用于将对象序列化为XML。
下面看一个最简单的例子:
public class A { public int a { get; set; } } public string XmlSerialize(T obj) { XmlSerializer xs = new XmlSerializer(typeof(T)); using (TextWriter tw = new StringWriter()) { xs.Serialize(tw, obj); return tw.ToString(); } } public T XmlDeserialize (string xml) where T : class { XmlSerializer xs = new XmlSerializer(typeof(T)); using (TextReader tr = new StringReader(xml)) { return xs.Deserialize(tr) as T; } } A objA = new A { a = 1 }; string xml = XmlSerialize(objA); var obj = XmlDeserialize (xml);
上面代码序列化出来的xml如下: