C# XmlSerializer 对象的Xml序列化和反序列化

.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="" xmlns:xsd=""> <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)

生活中若没有朋友,就像生活中没有阳光一样

C# XmlSerializer 对象的Xml序列化和反序列化

相关文章:

你感兴趣的文章:

标签云: