Writing XML to a file without overwriting previous data

前端 未结 4 1230
北荒
北荒 2020-12-04 00:00

I currently have a C# program that writes data to an XML file in using the .NET Framework.

if (textBox1.Text!=\"\" && textBox2.Text != \"\")
{
    X         


        
相关标签:
4条回答
  • 2020-12-04 00:23

    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; }
    }
    
    0 讨论(0)
  • 2020-12-04 00:24

    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/

    0 讨论(0)
  • 2020-12-04 00:31

    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>
    
    0 讨论(0)
  • 2020-12-04 00:34

    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.

    0 讨论(0)
提交回复
热议问题