Below is an extraction of our production code that presents core of the problem. After first run serialized list has 3 items correctly. But after running app second time (and more) each time 3 items are added to xml and to deserialized list. i.e after first run ABC is displayed but after second ABCABC and after third ABCABCABC.
Initialzier is required for other purposes and cannot be removed.
class Program
{
static void Main(string[] args)
{
var ser = new XmlSerializer(typeof(Ser));
Ser s;
try
{
using (var sr = new StreamReader("Test.xml"))
{
s = ser.Deserialize(sr) as Ser;
}
}
catch
{
s = new Ser();
}
using (var sw = new StreamWriter("Test.xml"))
{
ser.Serialize(sw, s);
}
foreach (var text in s.List)
{
Console.WriteLine(text);
}
}
}
public class Ser
{
public List<string> List { get; set; }= new List<string> {"A", "B", "C"}; //This initializer is a must
}
How to solve this problem?
You can serialize List<T>
as something else, e.g. array, then you will not have issue with XmlSerializer
:
public class Ser
{
[XmlIgnore]
public List<string> List { get; set; } = new List<string> { "A", "B", "C" }; //This initializer is a must
[XmlArray(nameof(List))]
public string[] SerializedList
{
get { return List.ToArray(); }
set { List = new List<string>(value); }
}
}
That would produce exactly same xml-file, but you will have extra public property (requirement for XmlSerializer
to work).