-->

Write to existing xml file without replacing it

2019-08-10 06:33发布

问题:

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.

回答1:

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.



回答2:

I would recommend parsing the entire xml document into memory, adding the new data, and then writing the whole document back out again.