XML文件序列化读取

原始XML文件



	
		
		
		
		
		
	
	
		
		
		
		
		
	

代码

Program.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

namespace ConsoleApp6SerializeXml
{
    [XmlRoot("School")]
    public class School
    {
        [XmlAttribute("headmaster")]
        public string headmaster { get; set; }
        [XmlElement("Grade")]
        public List grades { get; set; }
    }
}

Grade.cs

namespace ConsoleApp6SerializeXml
{
    public class Grade
    {
        [XmlAttribute("grade")]
        public int grade { get; set; }
        [XmlAttribute("teacher")]
        public string teacher { get; set; }
        [XmlElement("Student")]
        public List students { get; set; }
    }
}

Student.cs

namespace ConsoleApp6SerializeXml
{
    public class Student
    {
        [XmlAttribute("name")]
        public string name { get; set; }
        [XmlAttribute("age")]
        public int age { get; set; }
    }
}

结果

XML文件序列化读取_第1张图片

你可能感兴趣的:(C#,xml,C#)