简体   繁体   中英

Writing XML to a file without overwriting previous data

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 (eg, XmlReader / XmlWriter ) to interleave your reads, appends, and writes.

Just to add to Darin's answer, here is an article that I was getting ready to include in my own answer as a good reference for how to use XDocument to append nodes to an existing XML document:

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

Instead of writing out the XML manually, I would consider using the XmlSerializer along with a generic List. It looks like your needs are simple so memory usage isn't much of a concern. To add an item you will have to load the list and write it out 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM