在c#中写入XML文件(覆盖)

时间:2015-01-12 14:18:43

标签: c# xml

在我的迷你应用程序中,我有一个包含3个文本框的页面,我可以放置一些字符串。我希望这些文件保存在XML文件中。我的问题是,每次我引入一组新数据时,它都会被放在现有数据上。 这是我的代码:

protected void Button1_Click(object sender, EventArgs e){

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            DateTime start, end;
            DateTime.TryParse(TextBox1.Text, out start);
            DateTime.TryParse(TextBox2.Text, out end);
            float suma = 0.0f;
            float.TryParse(TextBox3.Text, out suma);
            using (XmlWriter writer = XmlWriter.Create("c:/users/ideapad/documents/visual studio 2013/Projects/XmlReader/XmlReader/rezervari.xml", settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Rezervari");

                writer.WriteStartElement("Rezervare");
                writer.WriteElementString("ID", ID);
                writer.WriteElementString("start", start.ToShortDateString());
                writer.WriteElementString("end", end.ToShortDateString());
                writer.WriteElementString("suma", suma.ToString());
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }

        }

我如何保留我拥有的并在旁边添加? (我看不到方法加载或其他东西)

2 个答案:

答案 0 :(得分:2)

我会使用LINQ to XML。以下是添加新元素的步骤:

  1. 使用XDocument.Load
  2. 加载XML文件
  3. 使用XElement constructor
  4. 创建新的XElement
  5. 使用XDocument.Root.Add方法将新元素添加到Root
  6. 使用XDocument.Save
  7. 保存文档

答案 1 :(得分:2)

我已经调整了您的代码,如下所示。这应该可以解决你的问题。

private void button1_Click(object sender, EventArgs e)
    {

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        DateTime start, end;
        DateTime.TryParse(textBox1.Text, out start);
        DateTime.TryParse(textBox2.Text, out end);
        float suma = 0.0f;
        float.TryParse(textBox3.Text, out suma);
        //Added this new line. Boolean parameter (true) here means append to existing content. 
        using (var stream = new StreamWriter("c:/users/ideapad/documents/visual studio 2013/Projects/XmlReader/XmlReader/rezervari.xml", true))
        {
            //Changed this line
            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Rezervari");

                writer.WriteStartElement("Rezervare");
                writer.WriteElementString("ID", ID);
                writer.WriteElementString("start", start.ToShortDateString());
                writer.WriteElementString("end", end.ToShortDateString());
                writer.WriteElementString("suma", suma.ToString());
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
    }