C# XML序列化/反序列化Howto

为项目组写了几个Howto的Case。

本文描述了一个用C#实现类的XML序列化及反序列化。
功能是生成一个类的实例,然后序列化成XML文件形式。
或者将一个已经序列化成文件的XML反序列化成类的实例。

为了充分展示Framework功能,在一个类里面嵌入另一个类,并且XML属性字段混杂。

Student.cs
[code=’c#’]
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace XMLHowto
{
[Serializable,XmlRoot(Namespace=”http://its.hpcc.tongji.edu.cn”)]
public class Student
{
[XmlElement]
public long Number;
[XmlElement]
public string Name;
[XmlElement]
public bool enabled;
[XmlElement]
public Dorm dorm;
}
}
[/code]

Dorm.cs
[code=’c#’]
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace XMLHowto
{
[Serializable, XmlRoot(Namespace = “http://its.hpcc.tongji.edu.cn”)]
public class Dorm
{
[XmlAttribute]
public string Name;
[XmlElement]
public string Number;
}
}
[/code]

Program.cs
[code=’c#’]
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace XMLHowto
{
class Program
{
static void Main(string[] args)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Student));

//序列化
FileStream fs1 = new FileStream(“./student.xml”, FileMode.Create, FileAccess.Write);
Student student = new Student();
Dorm dorm = new Dorm();

dorm.Name = “der drom”;
dorm.Number = “16-501-1”;

student.dorm = dorm;
student.enabled = true;
student.Number = 222222;
student.Name = “maojun”;

xmlSerializer.Serialize(fs1, student);

//反序列化
FileStream fs2 = new FileStream(“./student2.xml”, FileMode.Open, FileAccess.Read);
Student student2 = (Student)xmlSerializer.Deserialize(fs2);
}
}
}
[/code]

下载:用Visual Studio 2008打开
http://download.nocoo.us/Download/Archive/CSharpHowto/XML.rar

发表评论