There is such a class with a collection:
public class Animal { public string Sound { get; set; } } [Serializable] public class Example { public ObservableCollection<Animal> animals { get; set; } = new ObservableCollection<Animal>() { new Animal() {Sound = "Гав"}, new Animal() {Sound = "Мяу"}, new Animal() {Sound = "Кря"} }; public Example() { } } Serialize to XML and everything goes fine. The file looks like this:
<?xml version="1.0"?> <Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <animals> <Animal> <Sound>Гав</Sound> </Animal> <Animal> <Sound>Мяу</Sound> </Animal> <Animal> <Sound>Кря</Sound> </Animal> </animals> </Example> But after deserialization, there are 6 elements in the collection, instead of 3. As I understand it, this happens because when you create an instance of a class, the original 3 elements are added to the collection due to the constructor, and then 3 more are added when deserializing.
How to make sure that after deserialization there is nothing extra in the collection?