早就听说过xml,但一直没有用过,对于它的理解也是肤浅的很,最近有空接触了一下,虽然还是很肤浅,但总是有点了解了,也终于明白了它的用途之广了。下面的例子功能很简单,就是把一个实例化的类里的数据转化为xml文件,代码如下:
using System;
using System.IO;
using System.Xml.Serialization;
public enum Sex
{
male,female
}
[XmlRoot("Student",IsNullable = false,Namespace = "jah")]
public class Student
{
private string id;
private string name;
private Sex sex;
public Student()
{}
[XmlElement("ID")]
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
[XmlElement("Sex")]
public Sex Sex
{
get
{
return sex;
}
set
{
sex = value;
}
}
[XmlElement("Name")]
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
public class test
{
public static void
Main()
{
test t = new test();
t.SerializeStudent();
}
private void SerializeStudent()
{
Student s = new Student();
s.ID = "00056129";
s.Name = "jah";
s.Sex = Sex.male;
XmlSerializer ser = new XmlSerializer(typeof(Student));
FileStream fs = new FileStream("student.xml",FileMode.Create);
ser.Serialize(fs,s);
fs.Close();
}
}
这样,就产生了一个student.xml文件,它可以替你保存数据,以备后用,你也可以把它传给需要这份数据的程序。