编写的XML文件而不覆盖previous数据而不、文件、数据、XML

2023-09-02 10:33:01 作者:别样的青年别样的范儿≈

我现在有一个C#程序将数据写入到一个XML文件中使用.NET Framework。

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.

我有两个 Encoding.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);
}

,然后用这样的:

and then use like this:

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>