将 XML 写入文件而不覆盖以前的数据 [英] Writing XML to a file without overwriting previous data

查看:68
本文介绍了将 XML 写入文件而不覆盖以前的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个使用 .NET Framework 将数据写入 XML 文件的 C# 程序.

I currently have a C# program that writes data to an XML file in using the .NET Framework.

if (textBox1.Text!="" && textBox2.Text != "")
{
    XmlTextWriter Writer = new XmlTextWriter(textXMLFile.Text, null);
    Writer.WriteStartDocument();
    Writer.WriteStartElement("contact");
    Writer.WriteStartElement("firstName");
    Writer.WriteString(textBox1.Text);
    Writer.WriteEndElement();

    Writer.WriteEndElement();
    Writer.WriteEndDocument();
    Writer.Close();
}
else
{
    MessageBox.Show("Nope, fill that textfield!");
}

问题是每次我尝试保存新内容时我的 XML 文件都会被覆盖.

The problem is that my XML file gets overwritten every time I try to save something new.

我已经将 nullEncoding.UTF8 作为 XmlTextWriter 中的第二个参数,但它似乎不是什么更改非覆盖/覆盖功能.

I've had both null and Encoding.UTF8 for the second parameter in the XmlTextWriter but it doesn't seem to be what changes the non-overwrite/overwrite function.

推荐答案

您可以使用 XDocument:

public static void Append(string filename, string firstName)
{
    var contact = new XElement("contact", new XElement("firstName", firstName));
    var doc = new XDocument();

    if (File.Exists(filename))
    {
        doc = XDocument.Load(filename);
        doc.Element("contacts").Add(contact);
    }
    else
    {
        doc = new XDocument(new XElement("contacts", contact));
    }
    doc.Save(filename);
}

然后像这样使用:

if (textBox1.Text != "" && textBox2.Text != "")
{
    Append(textXMLFile.Text, textBox1.Text);
}
else
{
    MessageBox.Show("Nope, fill that textfield!");
}

这将创建/附加联系人到以下 XML 结构:

This will create/append the contact to the following XML structure:

<?xml version="1.0" encoding="utf-8"?>
<contacts>
  <contact>
    <firstName>Foo</firstName>
  </contact>
  <contact>
    <firstName>Bar</firstName>
  </contact>
</contacts>

这篇关于将 XML 写入文件而不覆盖以前的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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