XML Serializable Collection


/ Published in: C#
Save to your folder(s)

[Serializable]
[XmlRoot("items")]
public class ItemCollection : XmlSerializableCollection
{
}


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// <see cref="ICollection{T}"/> implementation which also provides xml serialization
  3. /// </summary>
  4. /// <typeparam name="T">The type of the contained elements</typeparam>
  5. public abstract class XmlSerializableCollection<T> : ICollection<T>, IXmlSerializable
  6. {
  7. #region Fields
  8.  
  9. private readonly IList<T> items = new List<T>();
  10.  
  11. #endregion
  12.  
  13. #region Properties
  14.  
  15. /// <summary>
  16. /// Obtains / Sets the element in a given ordinal position
  17. /// </summary>
  18. /// <param name="index">The ordinal position</param>
  19. public T this[int index]
  20. {
  21. get { return items[index]; }
  22. set { items[index] = value; }
  23. }
  24.  
  25. #endregion
  26.  
  27. #region ICollection<T> Members
  28.  
  29. public void Add( T item )
  30. {
  31. items.Add( item );
  32. }
  33.  
  34. public void Clear()
  35. {
  36. items.Clear();
  37. }
  38.  
  39. public bool Contains( T item )
  40. {
  41. return items.Contains( item );
  42. }
  43.  
  44. public void CopyTo( T[] array, int arrayIndex )
  45. {
  46. items.CopyTo( array, arrayIndex );
  47. }
  48.  
  49. public int Count
  50. {
  51. get { return items.Count; }
  52. }
  53.  
  54. public bool IsReadOnly
  55. {
  56. get { return items.IsReadOnly; }
  57. }
  58.  
  59. public bool Remove( T item )
  60. {
  61. return items.Remove( item );
  62. }
  63.  
  64. #endregion
  65.  
  66. #region IEnumerable<T> Members
  67.  
  68. public IEnumerator<T> GetEnumerator()
  69. {
  70. return items.GetEnumerator();
  71. }
  72.  
  73. #endregion
  74.  
  75. #region IEnumerable Members
  76.  
  77. IEnumerator IEnumerable.GetEnumerator()
  78. {
  79. return items.GetEnumerator();
  80. }
  81.  
  82. #endregion
  83.  
  84. #region IXmlSerializable Members
  85.  
  86. public virtual XmlSchema GetSchema()
  87. {
  88. return null;
  89. }
  90.  
  91. public virtual void ReadXml( XmlReader reader )
  92. {
  93. XmlSerializerHelper.DeserializeCollection( reader, items );
  94. }
  95.  
  96. public virtual void WriteXml( XmlWriter writer )
  97. {
  98. XmlSerializerHelper.Serialize( writer, this );
  99. }
  100.  
  101. #endregion
  102. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.