原始XML文件
XML
<?xml version="1.0" encoding="utf-8" ?>
<School headmaster="王校长">
<Grade grade="12" teacher="张老师">
<Student name="小米" age="18"/>
<Student name="小明" age="19"/>
<Student name="小蜜" age="17"/>
<Student name="小敏" age="16"/>
<Student name="小马" age="18"/>
</Grade>
<Grade grade="1" teacher="李老师">
<Student name="小红" age="8"/>
<Student name="小洪" age="9"/>
<Student name="小猴" age="7"/>
<Student name="肖红" age="6"/>
<Student name="小虹" age="8"/>
</Grade>
</School>
代码
Program.cs
cs
namespace ConsoleApp6SerializeXml
{
internal class Program
{
static void Main(string[] args)
{
DirectoryInfo path = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
StreamReader text = new StreamReader(path.Parent.Parent.FullName + "\\testxml.xml");
XmlSerializer serializer = new XmlSerializer(typeof(School));
School school = serializer.Deserialize(text) as School;
Console.WriteLine(school.headmaster);
foreach (Grade grade in school.grades)
{
Console.WriteLine(grade.grade);
Console.WriteLine(grade.teacher);
foreach (Student student in grade.students)
{
Console.WriteLine(student.name);
Console.WriteLine(student.age);
}
}
Console.ReadKey();
}
}
}
School.cs
cs
namespace ConsoleApp6SerializeXml
{
[XmlRoot("School")]
public class School
{
[XmlAttribute("headmaster")]
public string headmaster { get; set; }
[XmlElement("Grade")]
public List<Grade> grades { get; set; }
}
}
Grade.cs
cs
namespace ConsoleApp6SerializeXml
{
public class Grade
{
[XmlAttribute("grade")]
public int grade { get; set; }
[XmlAttribute("teacher")]
public string teacher { get; set; }
[XmlElement("Student")]
public List<Student> students { get; set; }
}
}
Student.cs
cs
namespace ConsoleApp6SerializeXml
{
public class Student
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlAttribute("age")]
public int age { get; set; }
}
}