c# - Add new child to existing child -
so have 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 new student xml file, use 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 problem is, adds new student root, not project1/students parant. how do this?
i've seen solutions xmltextwriter, not included anymore in 4.5...
i find using linq 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>
Comments
Post a Comment