Writing XML to a file without overwriting previous data

前端 未结 4 1235
北荒
北荒 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 
        { 
            {new Contact { FirstName = "Bob", LastName = "Dole" }},
            {new Contact { FirstName = "Bill", LastName = "Clinton" }}
        };
    
        XmlSerializer serializer = new XmlSerializer(typeof(List));
        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; }
    }
    

提交回复
热议问题