C# XmlSerializer 对象的Xml序列化和反序列化
原创
©著作权归作者所有:来自51CTO博客作者郎涯工作室的原创作品,请联系作者获取转载授权,否则将追究法律责任
.Net程序执行时,对象都驻留在内存中;内存中的对象如果需要传递给其他系统使用;或者在关机时需要保存下来以便下次再次启动程序使用就需要序列化和反序列化。
System.Xml.Serialization命名空间中有一系列的特性类,用来控制复杂类型序列化。例如XmlElementAttribute、XmlAttributeAttribute、XmlArrayAttribute、XmlArrayItemAttribute、XmlRootAttribute等等。
可以使用XmlElement指定属性序列化为子节点(默认情况会序列化为子节点);或者使用XmlAttribute特性制定属性序列化为Xml节点的属性;还可以通过XmlIgnore特性修饰要求序列化程序不序列化属性。
数组的Xml序列化需要使用XmlArrayAttribute和XmlArrayItemAttribute;XmlArrayAttribute指定数组元素的Xml节点名,XmlArrayItemAttribute指定数组元素的Xml节点名。
看一个小例子,有一个自定义类Cat,Cat类有三个属性分别为Color,Saying,Speed。
类定义:
[XmlRoot("CatsInfo")]
public class CatCollection
{
[XmlArray("Cats"), XmlArrayItem("Cat")]
public Cat[] Cats { get; set; }
}
[XmlRoot("Cat")]
public class Cat
{
// 定义Color属性的序列化为cat节点的属性
[XmlAttribute("color")]
public string Color { get; set; }
// 要求不序列化Speed属性
[XmlIgnore]
public int Speed { get; set; }
// 设置Saying属性序列化为Xml子元素
[XmlElement("saying")]
public string Saying { get; set; }
}
测试:
//声明一个猫咪对象
var cWhite = new Cat { Color = "White", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" };
var cBlack = new Cat { Color = "Black", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" };
CatCollection cc = new CatCollection { Cats = new Cat[] { cWhite, cBlack } };
//序列化这个对象
XmlSerializer serializer = new XmlSerializer(typeof(CatCollection));
//将对象序列化输出到控制台
FileStream stream = new FileStream("test.Xml", FileMode.OpenOrCreate);
serializer.Serialize(stream, cc);
结果:
<?xml version="1.0"?>
<CatsInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Cats>
<Cat color="White">
<saying>White or black, so long as the cat can catch mice, it is a good cat</saying>
</Cat>
<Cat color="Black">
<saying>White or black, so long as the cat can catch mice, it is a good cat</saying>
</Cat>
</Cats>
</CatsInfo>
使用XmlSerializer序列化,初始化XmlSerializer对象时最好使用下面两个构造函数否则会引起内存泄漏。
XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)