将节点附加到 XML 文件

我有一个包含学校元素的 XML 文件。


 <Classrooms>

  <Classroom ID="Mrs.S">

   <Students>

    <Student>

     <Name> Billy Blue </Name>

     <Grade> 1 </Grade>

     <Sex> Male </Sex>

     <Age> 7 </Age>

     <Picture> c:/School/Students/BillyBlue </Picture>

   </Student>

  </Students>

 </Classroom>

</Classrooms>

我想在使用 Windows 表单时附加不同的学生。这是我的代码。它们目前被添加到教室标签之后,我希望它们在学生节点中。


    {

        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(ConfigurationManager.AppSettings.Get("studentFile"));

        XmlNode student = xmlDoc.CreateElement("Student");

        XmlNode name = xmlDoc.CreateElement("Name");

        name.InnerText = tBName.Text;

        student.AppendChild(name);

        XmlNode grade = xmlDoc.CreateElement("Grade");

        grade.InnerText = tBGrade.Text;

        student.AppendChild(grade);

        XmlNode sex = xmlDoc.CreateElement("Sex");

        sex.InnerText = tbSex.Text;

        student.AppendChild(sex);

        XmlNode age = xmlDoc.CreateElement("Age");

        age.InnerText = tBAge.Text;

        student.AppendChild(age);

        XmlNode picture = xmlDoc.CreateElement("Picture");

        picture.InnerText = tBPicture.Text;

        student.AppendChild(picture);



        xmlDoc.DocumentElement.AppendChild(student);

        xmlDoc.Save(ConfigurationManager.AppSettings.Get("studentFile"));

    }


温温酱
浏览 120回答 2
2回答

慕仙森

有了LinqtoXml,这很容易做到。强烈建议使用Linq To XmL:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/adding-elements-attributes-and-nodes-to-an-xml-treetry{&nbsp; &nbsp; XDocument xmlDoc = XDocument.Load("StudentDoc.xml"));&nbsp; &nbsp; xmlDoc.Element("Students").Add(&nbsp; &nbsp; new XElement("Student",&nbsp;&nbsp; &nbsp; new XElement("Name", "Peter"),&nbsp; &nbsp; new XElement("Grade", 10.0),&nbsp;&nbsp; &nbsp; new XElement("Sex", "Male")));&nbsp; &nbsp; xmlDoc.Save("StudentDoc.xml"));}catch{}然后你可以做不同的事情,比如排序:IEnumerable<decimal> names =&nbsp;&nbsp;&nbsp; &nbsp; from student in root.Elements("Students")&nbsp;&nbsp;&nbsp; &nbsp; orderby student.Name&nbsp;&nbsp;&nbsp; &nbsp; select student.Name;&nbsp;&nbsp;foreach (string name in names)&nbsp;&nbsp;&nbsp; &nbsp; Console.WriteLine(name);&nbsp;

喵喔喔

您可以找到“学生”节点XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(ConfigurationManager.AppSettings.Get("studentFile"));XmlElement root = xmlDoc.DocumentElement;XmlNode node = root.SelectSingleNode("//Classrooms/Classroom/Students");然后最后你可以将新节点附加到这个节点node.AppendChild(student);//xmlDoc.DocumentElement.AppendChild(student);xmlDoc.Save(ConfigurationManager.AppSettings.Get("studentFile"));
打开App,查看更多内容
随时随地看视频慕课网APP