【发布时间】:2013-09-09 23:24:12
【问题描述】:
我有一个现有的 XML 文件,我想在不更改格式的情况下附加它。现有文件如下所示:
<Clients>
<User username="farstucker">
<UserID>1</UserID>
<DOB />
<FirstName>Steve</FirstName>
<LastName>Lawrence</LastName>
<Location>NYC</Location>
</User>
</Clients>
如何使用这种格式添加其他用户?我现有的代码是:
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 来附加数据,但我不确定是否可以在不弄乱文件的情况下保持现有格式(和空标签)。
非常感谢您提供的任何建议。
编辑我已更改代码以读取原始 XML,但文件不断被覆盖。
【问题讨论】:
-
不要使用
new XmlTextWriter()。自 .NET 2.0 以来,这已被弃用。请改用XmlWriter.Create()。