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>
source share