主要的程序代码都放在Main 函数的try代码段里. 首先创建一个XmlSerializer对象并指明一个System.Type 对象来告诉反串行化程序要创建的对象的类型. typeof操作符为Theater类返回一个System.Type 对象. 然后, 打开一个文件流读取输入的XML文件. 调用XmlSerializer的Deserialize方法, 并把文件流传递给它. Deserialize 返回对Theater对象的引用. Theater和Movie 对象中的ToString方法能够让你简单的输出它们.
将对象串行化到XML里
从一个Theater对象生成XML数据同样是容易的. 表E中的程序,XmlOut, 就是将一个Theater对象串行化到XML 文件里. 这个程序通过命令行执行, 你需要指明输出的XML文件.
表E
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Articles.TechRepublic.XmlSerialization;
public class XmlOut
{
// Returns a populated Theater object.
public static Theater GetTheater()
{
Movie movie = new Movie();
movie.Title = "O Brother, Where Art Thou?";
movie.Minutes = 102;
movie.Showings = new DateTime[3];
movie.Showings[0] = new DateTime( 2001, 8, 2, 13, 15, 0 );
movie.Showings[1] = new DateTime( 2001, 8, 2, 16, 30, 0 );
movie.Showings[2] = new DateTime( 2001, 8, 2, 19, 55, 0 );
Theater theater = new Theater();
theater.Name = "Hollywood Movies 10";
theater.Phone = "(972)555-154";
theater.Movies = new Movie[1];
theater.Movies[0] = movie;
return theater;
}
public static void Main( string[] args )
{
if ( args.Length != 1 )
{
Console.WriteLine( "Usage: XmlOut outfile.xml" );
return;
}
try
{
Theater theater = GetTheater();
// Serialize the Theater object to an XML file.
XmlSerializer xs = new XmlSerializer( typeof ( Theater ) );
FileStream fs = new FileStream( args[0], FileMode.Create );
xs.Serialize( fs, theater );
}
catch ( Exception x )
{
Console.WriteLine( "Exception: " x.Message );
}
}
}
Invocation:
>XmlOut theaterOut.xml
theaterOut.xml contents:
<?xml version="1.0"?>
<theater
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>Hollywood Movies 10</name>
<phone>(972)555-154</phone>
<movie minutes="102">
<title>O Brother, Where Art Thou?</title>
<showing>13:15:00.0000000-06:00</showing>
<showing>16:30:00.0000000-06:00</showing>
<showing>19:55:00.0000000-06:00</showing>
</movie>
</theater>
主要的程序代码都放在Main 函数的try代码段里. 首先通过GetTheater帮助函数创建一个Theater对象. 然后, 打开一个文件流来生成输出的XML 文件. 调用XmlSerializer的Serialize方法, 传递给它文件流和Theater对象. 就是这样简单--XML文件生成了!
输出的theater 元素包含了为模板和模板实例命名空间生成的XML命名空间属性(xmlns), 虽然在这两个命名空间里这些数据并不代表任何东西. showing元素中的-06:00 指的是美国中部时间, 或者说GMT时间再减去个小时, 也就是我所在的时区.
移动数据是小菜一碟
XmlSerializer 使得在对象和XML间移动数据变得非常容易, 只要在类里加上XML映射属性. 但是对于更复杂的对象模型, 手工的创建XML映射会变得非常的麻烦而且容易出错. 在我的下一篇文章里, 我将告诉你如何自动化这个工作并实现对你的XML数据的更严格的控制.