CularBytes
CularBytes

Reputation: 10321

Add new child to existing child

So I have this kind of XML file:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <Project1>
 <Students>
   <Student>
     <name>test2</name>
     <studentnum>01</studentnum>
   </Student>
 </Students>
</Project1>
</root>

To add a new Student to this XML file, I use this code (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"));

But the problem is, it adds a new Student to the Root, not to the Project1/Students parant. How do I do this?

I've seen solutions with XmlTextWriter, but that is not included anymore in 4.5...

Upvotes: 1

Views: 75

Answers (2)

L.B
L.B

Reputation: 116178

I find using Linq To Xml easier

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);

OUTPUT:

<?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>

Upvotes: 4

Chris Rosete
Chris Rosete

Reputation: 1258

Try this:

XmlNode studentsNode= doc.SelectSingleNode("Project1/Students");

studentsNode.AppendChild(Student);

Upvotes: 0

Related Questions