Appending an existing XML file with XmlWriter

user3105160 picture user3105160 · Jan 4, 2014 · Viewed 66.5k times · Source

I've used the following code to create an XML file:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
   xmlWriter.WriteStartDocument();
   xmlWriter.WriteStartElement("School");
   xmlWriter.WriteEndElement();
   xmlWriter.WriteEndDocument();
   xmlWriter.Close();
 }

I need to insert nodes dynamically creating the following structure:

<?xml version="1.0" encoding="utf-8"?>
<School />
   <Student>
      <FirstName>David</FirstName>
      <LastName>Smith</LastName>
   </Student>
   ...
   <Teacher>
      <FirstName>David</FirstName>
      <LastName>Smith</LastName>
   </Teacher>
   ...
</School>

How can I do it? The values of "FirstName" and "LastName" should be read from the keyboard and the values ​​can be entered at any time, of course under existing.

Answer

Gokul E picture Gokul E · Jan 4, 2014

you can use Linq Xml

XDocument doc = XDocument.Load(xmlFilePath);
XElement school = doc.Element("School");
school.Add(new XElement("Student",
           new XElement("FirstName", "David"),
           new XElement("LastName", "Smith")));
doc.Save(xmlFilePath);

Edit

if you want to add Element to Existing <Student>, just add an Attribute before

school.add(new XElement("Student",
           new XAttribute("ID", "ID_Value"),
           new XElement("FirstName", "David"),
           new XElement("LastName", "Smith")));

Then you can add further Details to the Existing <Student> by search -> get -> add

XElement particularStudent = doc.Element("School").Elements("Student")
                                .Where(student => student.Attribute("ID").Value == "SearchID")
                                .FirstOrDefault();
if(particularStudent != null)
    particularStudent.Add(new XElement("<NewElementName>","<Value>");