I have a custom serializable generic collection, defined (a simplified example) like this:
[Serializable]
public class ArrayOfItems<T> : IEnumerable<T>
{
[XmlAttribute("Setting")]
public bool Setting { get; set; } = false;
[XmlAnyElement]
public List<T> Items { get; set; } = new List<T>();
public IEnumerator<T> GetEnumerator()
{
return Items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
IEnumerator iterator = ((IEnumerable<T>)this).GetEnumerator();
while ( iterator.MoveNext() )
{
yield return iterator.Current;
}
}
public void Add( T Object )
{
Items.Add(Object );
}
}
I create an instance and serialize it using xml serializer:
ArrayOfItems<int> ints = new();
ints.Items.Add(0);
ints.Items.Add(1);
using (StreamWriter writer = new
StreamWriter(@"C:\test.xml", false, System.Text.Encoding.Unicode))
{
XmlSerializer serializer = new(ints.GetType());
serializer.Serialize(writer, ints);
writer.Flush();
writer.Close();
}
And here is the file I get:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<int>0</int>
<int>1</int>
</ArrayOfInt>
Does anyone understand why the bool Setting property is not serialized?