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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With