附加现有的XML文件 [英] Appending an existing XML file

查看:75
本文介绍了附加现有的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个想要在不更改格式的情况下附加的XML文件。现有文件看起来像这样:

I have an existing XML file that I would like to append without changing the format. Existing File looks like this:

<Clients>
  <User username="farstucker">
    <UserID>1</UserID>
    <DOB />
    <FirstName>Steve</FirstName>
    <LastName>Lawrence</LastName>
    <Location>NYC</Location>
  </User>
</Clients>

如何使用此格式添加其他用户?我现有的代码是:

How can I add another user using this format? My existing code is:

        string fileLocation = "clients.xml";

        XmlTextWriter writer;

        if (!File.Exists(fileLocation))
        {
            writer = new XmlTextWriter(fileLocation, null);
            writer.WriteStartDocument();

            // Write the Root Element
            writer.WriteStartElement("Clients");

            // End Element and Close
            writer.WriteEndElement();
            writer.Close();
        }
// Append new data here

我已经考虑过使用XmlDocument Fragment追加数据,但是我不确定我是否可以保持现有格式(和空标签)而不弄乱文件。

Ive thought about using XmlDocument Fragment to append the data but Im not certain if I can maintain the existing format ( and empty tags ) without messing up the file.

您能提供的任何建议都将受到赞赏。

Any advice you could give is much appreciated.

编辑Ive更改了代码以读取原始XML,但文件不断被覆盖。

EDIT Ive changed the code to read the original XML but the file keeps getting overwritten.

推荐答案

您应该使用XmlDocument类加载整个文件,在内存中对其进行修改,然后将内容写回以替换原始文件。不用担心,它不会弄乱您的标记,您甚至可以使用 PreserveWhitespace 属性( http://msdn.microsoft.com/en-us/ library / system.xml.xmldocument.preservewhitespace.aspx )。

You should use the XmlDocument class to load the whole file, modify it in memory and then write the contents back replacing the original file. Don't worry, it won't mess up your markup, and you can even ask it to preserve non-significant whitespace in the original document using the PreserveWhitespace property (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).

这篇关于附加现有的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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