C# 使用XML序列化对象(一)
在System.Xml.Serialization命名空间中提供了XML序列化类XmlSerializer用于将对象序列化为XML。
下面看一个最简单的例子:
public class A { public int a { get; set; } } public string XmlSerialize<T>(T obj) { XmlSerializer xs = new XmlSerializer(typeof(T)); using (TextWriter tw = new StringWriter()) { xs.Serialize(tw, obj); return tw.ToString(); } } public T XmlDeserialize<T>(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<A>(xml);
上面代码序列化出来的xml如下:
<?xml version="1.0" encoding="utf-16"?> <A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <a>1</a> </A>