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

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

问题描述

我现在有一个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>

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

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