XmlTextWriter problem

Last post 11-08-2009 7:04 AM by Martin_Honnen. 2 replies.

Sort Posts:

  • XmlTextWriter problem

    11-07-2009, 3:01 PM
    • Member
      5 point Member
    • aykt87
    • Member since 08-25-2009, 10:06 PM
    • Posts 25

    Hello;


    I want to create a XML file to keep my records from C#. I have a windows form that takes records and add them to XML file. My code is like this:


                XmlTextWriter textWriter = new XmlTextWriter(@"c:\student.xml", System.Text.Encoding.UTF8);
                
                // Opens the document
    
                textWriter.WriteStartDocument();
    
                // Write first element
    
                textWriter.WriteStartElement("students");
    
                textWriter.WriteStartElement("student");
    
                // Write next element
    
                textWriter.WriteStartElement("id");
    
                textWriter.WriteString(this.Id);
    
                textWriter.WriteEndElement();
    
                // Write one more element
    
                textWriter.WriteStartElement("name"); 
                
                textWriter.WriteString(this.Name);
    
                textWriter.WriteEndElement();
    
                // Write one more element
    
    
                textWriter.WriteStartElement("surname");
    
                textWriter.WriteString(this.Surname);
    
                textWriter.WriteEndElement();
    
                // Write one more element
    
    
                textWriter.WriteStartElement("department");
    
                textWriter.WriteString(this.Department);
    
                textWriter.WriteEndElement();
    
                // Ends the document.
    
                textWriter.WriteEndDocument();
    
                // close writer
    
                textWriter.Close();


    What i click the add button it add the new record and deletes the old one. What i want to is adding new records without deletion. Need Help, Thanks;

    Sorry about my english...

  • Re: XmlTextWriter problem

    11-07-2009, 4:27 PM

    Hello,


    the problem seems to be, that you are alyways replacing the content of the file. You can open the file in append mode, but this would not produce valid xml, since there would not be a single root node after saving the second time. You could do it manually (reading all students, create the rootnode and add all students plus the new one) or you could use XMLSerialization to serialize/deserialize the complete collection of students.


    Good luck,

    Bernhard Kircher

  • Re: XmlTextWriter problem

    11-08-2009, 7:04 AM
    Answer

    With .NET 3.5 you can use LINQ to XML to add elements to an XML document.

    Martin Honnen --- MVP XML
    My blog
Page 1 of 1 (3 items)