除了SOAP和二进制式化程序外,System.Xml.dll程序集提供了第三种格式化程序:System.Xml.Serialization.XmlSerializer。与XML数据被包含在一个SOAP消息中相反,该方式可以被用来将给定对象的公共状态持久化为一个纯XML。使用这种类型与使用SoapFormatter或BinaryFormatter类型有一点不同。例如假定使用了System.Xml.SerialZation的命名空间:
using JamesBondCarCS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace XmlSerializerCS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with object XmlSerializer *****\n");
// 建立一个JamesBondCar并设定状态
JamesBondCar jbc = new JamesBondCar();
jbc.canFly = true;
jbc.canSubmerage = false;
jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 };
jbc.theRadio.hasSubWoofers = true;
// 将car以二进制格式保存到指定文件中
SaveAsXmlFormat(jbc, "CarData.dat");
Console.ReadLine();
}
static void SaveAsXmlFormat(object objGraph, string fileName)
{
// 将对象以XML格式保存到CarData.xml文件中
XmlSerializer xmlFormat = new XmlSerializer(typeof(JamesBondCar));
using (Stream fStream = new FileStream(fileName,
FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormat.Serialize(fStream, objGraph);
}
Console.WriteLine("=> Saved car in XML format!");
}
}
}
JamesBondCar实例类的实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JamesBondCarCS
{
[Serializable]
public class JamesBondCar: Car
{
public bool canFly;
public bool canSubmerage;
}
}
JamesBondCar是继承Car的成员字段和成员函数,Car类的实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JamesBondCarCS
{
[Serializable]
public class Car
{
public Radio theRadio = new Radio();
public bool isHatchBack;
}
}
与此同时还要创建一个Radio的类,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JamesBondCarCS
{
[Serializable]
public class Radio
{
public bool hasTweeters;
public bool hasSubWoofers;
public double[] stationPresets;
[NonSerialized]
public string radioID = "XF-553RR6";
}
}
关键的不同点是XmlSerializer类型需要你指定类型信息表示要序列化的类。
如果查看新生成的XML文件(假设调用了Main()中的新方法),可以看到如下所示的XML数据:
XmlSerializer要求对象图中的所有序列化类型支持默认的构造函数,如果没有,在运行时收到InvalidOperationException。
小结:这是简单的XmlSerializer序列化对象,以上代码简单的方法说明了Xml序列化,.Net系统类库为我们做了大量的工作,但在现实中的业务需求往往比较复杂。