I would like to know how to ignore a specific item/index of a List
from being serialized using XmlSerializer
.
For example, co
I suspect you are actually trying to solve an XY problem where the real problem is the one described in the question Deserializing List with XmlSerializer Causing Extra Items: when you serialize and deserialize a collection property that has default items added in the constructor, the default items get duplicated, because the deserialized default items get added to the latest default items.
That answer to that question provides one workaround, namely to move initialization of the default collection entries out of the constructor. If that's not convenient, you can instead introduce a proxy array property and serialize that instead of the underlying collection:
[Serializable]
public class Ball
{
public Ball()
{
Points = new List() { 1 };
IsEnabled = false;
}
public bool IsEnabled { get; set; }
[XmlIgnore]
public List Points { get; set; }
[XmlArray("Points")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int[] SerializablePoints
{
get
{
return (Points == null ? null : Points.ToArray());
}
set
{
Points = ListExtensions.Initialize(Points, value);
}
}
}
public static class ListExtensions
{
public static List Initialize(List list, T[] value)
{
if (value == null)
{
if (list != null)
list.Clear();
}
else
{
(list = list ?? new List(value.Length)).Clear();
list.AddRange(value);
}
return list;
}
}
For an explanation of why the property must be an array, see XML Deserialization of collection property with code defaults.