I encountered following issue,
I first write to my xml file like this:
XmlTextWriter writer = new XmlTextWriter("course.xml", null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Course");
writer.WriteAttributeString("title", "Examle");
writer.WriteAttributeString("started", "true");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
And xml output I get is:
<?xml version="1.0"?>
<Course title="Example" started="true" />
After that I want to write more data to this xml file so I use my code again:
XmlTextWriter writer = new XmlTextWriter("course.xml", null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Course");
writer.StartElement("Level");
writer.StartElement("Module");
writer.EndElement();
writer.EndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
And the xml output is:
<?xml version="1.0"?>
<Course>
<Level>
<Module>
</Module>
</Level>
</Course>
So it replaces my original data, and all attributes in the course tag. Therefore I need a way where it doesn't replace data, but instead add it inside existing tags.
I would recommend parsing the entire xml document into memory, adding the new data, and then writing the whole document back out again.
XML files are just sequential text files. They are not a database or a random-access file. There is no way to just write into the middle of them.