C# 读写XML文件

1、写XML,内容如下:


<?xml version="1.0" encoding="UTF-8"?>
<Students> 

<Student1>student1</Student1> 

<Student2>student2</Student2> 

</Students>


C#代码:

public void WriteXml()
       {
           string path = "D:\\test.xml";
           XmlDocument xmlDocument = new XmlDocument();

           //xml 声明。
           XmlDeclaration dec = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
           xmlDocument.AppendChild(dec);

           XmlElement students = xmlDocument.CreateElement("Students");
           xmlDocument.AppendChild(students);

           XmlElement student1 = xmlDocument.CreateElement("Student1");
           student1.InnerText = "student1";
           students.AppendChild(student1);

           XmlElement student2 = xmlDocument.CreateElement("Student2");
           student2.InnerText = "student2";
           students.AppendChild(student2);

           xmlDocument.Save(path);
       }

2、读XML


C#代码:

 public void ReadXml()
       {
           string path = "D:\\test.xml";
           XmlDocument xmlDocument = new XmlDocument();
           xmlDocument.Load(path);

           var student1Element = (XmlElement)xmlDocument.SelectSingleNode("/Students/Student1");
           string student1 = student1Element.InnerText;

           Console.WriteLine(student1);
       }

你可能感兴趣的:(C# 读写XML文件)