所以我有这种XML文件:
<?xml version="1.0" encoding="utf-8"?>
<root>
<Project1>
<Students>
<Student>
<name>test2</name>
<studentnum>01</studentnum>
</Student>
</Students>
</Project1>
</root>
要将新学生添加到此XML文件,我使用此代码(C#)
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("datastorage.xml"));
XmlElement Student = doc.CreateElement("Student");
XmlElement name = doc.CreateElement("name");
XmlText xmlName = doc.CreateTextNode(txtStudentName1.Text);
XmlElement studentnum = doc.CreateElement("studentnum");
XmlText xmlStudentnum = doc.CreateTextNode(txtStudentNum1.Text);
name.AppendChild(xmlName);
studentnum.AppendChild(xmlStudentnum);
Student.AppendChild(name);
Student.AppendChild(studentnum);
doc.DocumentElement.AppendChild(Student);
doc.Save(Server.MapPath("datastorage.xml"));
但问题是,它为Root添加了一个新学生,而不是Project1 / Student parant。 我该怎么做?
我已经看过使用XmlTextWriter的解决方案,但在4.5中不再包含...
答案 0 :(得分:4)
我发现使用Linq To Xml更容易
var xDoc = XDocument.Load(filename);
xDoc.Descendants("Project1").Descendants("Students")
.First()
.Add(new XElement("Student",
new XElement("name","test3"),
new XElement("studentnum","03")));
xDoc.Save(filename);
输出:
<?xml version="1.0" encoding="utf-8"?>
<root>
<Project1>
<Students>
<Student>
<name>test2</name>
<studentnum>01</studentnum>
</Student>
<Student>
<name>test3</name>
<studentnum>03</studentnum>
</Student>
</Students>
</Project1>
</root>
答案 1 :(得分:0)
试试这个:
XmlNode studentsNode= doc.SelectSingleNode("Project1/Students");
studentsNode.AppendChild(Student);