Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing XML to a file without overwriting previous data

Tags:

c#

.net

file-io

xml

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!");
}

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

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.

like image 502
Johnston Avatar asked Dec 13 '22 11:12

Johnston


2 Answers

You could use a 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!");
}

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>
like image 99
Darin Dimitrov Avatar answered Jan 08 '23 00:01

Darin Dimitrov


The only way to add data to an XML file is to read it in, add the data, and then write out the complete file again.

If you don't want to read the entire file into memory, you can use the streaming interfaces (e.g., XmlReader/XmlWriter) to interleave your reads, appends, and writes.

like image 27
Stephen Cleary Avatar answered Jan 07 '23 22:01

Stephen Cleary