Writing XML to a file without overwriting previous data

前端 未结 4 1234
北荒
北荒 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: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:

    
    
      
        Foo
      
      
        Bar
      
    
    

提交回复
热议问题