1
public class Person {
    [XmlElement]
    public int Id { get; set; }
    [XmlElement]
    public string Name { get; set; }
}
//=========
XmlSerializer formatter = new XmlSerializer(typeof(List<Person>));

        List<Person> personList = new List<Person>();
        personList.Add(new Person { Id = 5, Name = "Bob" });
        personList.Add(new Person { Id = 15, Name = "Tom" });
        Person kate = new Person { Id = 115, Name = "Kate" };
        personList.Add(kate);

        string filePath = @"C:\DELEteME.xml";

        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate)) {
            formatter.Serialize(fs, personList);
        }

So far everything is ok:

<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Id>5</Id>
    <Name>Bob</Name>
  </Person>
  <Person>
    <Id>15</Id>
    <Name>Tom</Name>
  </Person>
  <Person>
    <Id>115</Id>
    <Name>Kate</Name>
  </Person>
</ArrayOfPerson>

But after I delete an element from personList and try to serialize it again

        personList.Remove(kate);
        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate)) {
            formatter.Serialize(fs, personList);
        }   

It serializing to this:

<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Id>5</Id>
    <Name>Bob</Name>
  </Person>
  <Person>
    <Id>15</Id>
    <Name>Tom</Name>
  </Person>
</ArrayOfPerson><Id>115</Id>
    <Name>Kate</Name>
  </Person>
</ArrayOfPerson>

It just removes <Person> and of course I can't work with a file anymore because of multiple namespaces. Can't figure out why this is happening and how to fix this. Thanks

uturupu
  • 85
  • 3
  • 8

1 Answers1

1

Use FileMode.Create instead of FileMode.OpenOrCreate. From the docs:

FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate

Essentially, using OpenOrCreate will not truncate the file (set its size to 0 bytes) if it exists. If the content you are writing is smaller than the existing file size then you'll see garbage in the 'unused' part.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45