您的位置:首页 > 其它

创建指定的xml文档三

2008-12-07 21:52 176 查看
要生成的xml是:

<?xml version="1.0" encoding="utf-16"?>

<学校 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<学生 姓名="李四" 学号="0443111121">

<分数 语文="90" 数学="89" 英语="85" />

</学生>

<学生 姓名="李四" 学号="0443111121">

<分数 语文="90" 数学="89" 英语="85" />

</学生>

</学校>

先序列化xml文件

[XmlRoot("学校")]
public class School
{
List<Student> stu = new List<Student>();
[XmlElement(ElementName = "学生")]
public List<Student> Stu
{
get { return stu; }
set { stu = value; }
}
}

public class Student
{
private string name;
[XmlAttribute(AttributeName="姓名")]
public string Name
{
get { return name; }
set { name = value; }
}
private string stuID;
[XmlAttribute(AttributeName="学号")]
public string StuID
{
get { return stuID; }
set { stuID = value; }
}
private Score score = new Score();
[XmlElement(ElementName = "分数")]
public Score Score
{
get{return score;}
set{score=value;}
}
}

public class Score
{
private string chinese;
[XmlAttribute(AttributeName = "语文")]
public string Chinese
{
get { return chinese; }
set { chinese = value; }
}
private string math;
[XmlAttribute(AttributeName = "数学")]
public string Math
{
get { return math; }
set { math = value; }
}
private string english;
[XmlAttribute(AttributeName = "英语")]
public string English
{
get { return english; }
set { english = value; }
}
}

School s = new School();
Student stu = new Student();
stu.Name = "张三";
stu.StuID = "0443111241";
Score sco = new Score();
sco.Chinese = "95";
sco.English = "85";
sco.Math = "88";
stu.Score = sco;
s.Stu.Add(stu);

stu.Name = "李四";
stu.StuID = "0443111121";
sco.Chinese = "90";
sco.English = "85";
sco.Math = "89";
stu.Score = sco;
s.Stu.Add(stu);
XmlSerializer mySerializer = new XmlSerializer(typeof(School));
StringBuilder sb =new StringBuilder();
XmlWriter xw = XmlWriter.Create(sb);
mySerializer.Serialize(xw, s);
xw.Close();
richTextBox1.Text = sb.ToString();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: