Search code examples
c#xmlwinformsvisual-studioxmlwriter

Write to existing xml file without replacing it's contents (XmlWriter)


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.


Solution

  • 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.