写入现有的 xml 文件而不替换其内容 (XmlWriter) [英] Write to existing xml file without replacing it's contents (XmlWriter)

查看:36
本文介绍了写入现有的 xml 文件而不替换其内容 (XmlWriter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题,

我首先像这样写入我的 xml 文件:

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();

我得到的 xml 输出是:

And xml output I get is:

<?xml version="1.0"?>
<Course title="Example" started="true" />

之后我想向这个 xml 文件写入更多数据,所以我再次使用我的代码:

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();

xml 输出为:

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

推荐答案

XML 文件只是顺序文本文件.它们不是数据库或随机访问文件.没办法只写到中间.

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.

这篇关于写入现有的 xml 文件而不替换其内容 (XmlWriter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆