Write to existing xml file without replacing it

2019-08-10 06:09发布

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.

2条回答
叛逆
2楼-- · 2019-08-10 06:50

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

查看更多
放我归山
3楼-- · 2019-08-10 06:55

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.

查看更多
登录 后发表回答