Writing XML to a file without overwriting previous data

I currently have a C # program that writes data to an XML file 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 is overwritten every time I try to save something new.

I had both null and Encoding.UTF8 for the second parameter in XmlTextWriter , but it doesn't seem to change the function without overwriting / rewriting.

+4
source share
4 answers

You can use 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 / add a 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> 
+6
source

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

If you do not want to read the entire file in memory, you can use stream interfaces (e.g. XmlReader / XmlWriter ) to alternate your reads, additions, and writes.

+5
source

To add an answer to Darin, here is an article I was about to include in my own answer as a good reference on how to use XDocument to add nodes to an existing XML document:

http://davidfritz.wordpress.com/2009/07/10/adding-xml-element-to-existing-xml-document-in-c/

+1
source

Instead of writing XML manually, I would consider using XmlSerializer along with a general list. It seems your needs are simple, so memory usage is not a big concern. To add an item, you will need to download the list and write it again.

 void Main() { var contacts = new List<Contact> { {new Contact { FirstName = "Bob", LastName = "Dole" }}, {new Contact { FirstName = "Bill", LastName = "Clinton" }} }; XmlSerializer serializer = new XmlSerializer(typeof(List<Contact>)); TextWriter textWriter = new StreamWriter(@"contacts.xml"); serializer.Serialize(textWriter, contacts); textWriter.Close(); } public class Contact { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } } 
+1
source

All Articles