Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes

Tags:

I'm having a situation here, I need my class to be inherited from List<ItemType>, but when I do this XmlSerializer does not serialize any property or field declared in my class, the following sample demonstrates:

public partial class Form1 : Form {     public Form1()     {         InitializeComponent();         DoSerialize();     }     private void DoSerialize()     {         MyClass obj = new MyClass();         obj.Add(1);         obj.Add(2);         obj.Add(3);         XmlSerializer s = new XmlSerializer(typeof(MyClass));         StringWriter sw = new StringWriter();         s.Serialize(sw, obj);     } } [Serializable] [XmlRoot] public class MyClass : List<int> {     public MyClass()     {     }     int myAttribute = 2011;     [XmlAttribute]     public int MyAttribute     {         get         {             return myAttribute;         }         set         {             myAttribute = value;         }     } } 

the resulting XML:

<?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>1</int>   <int>2</int>   <int>3</int> </ArrayOfInt> 
like image 634
Esam Bustaty Avatar asked Feb 21 '11 17:02

Esam Bustaty


People also ask

What is XmlSerializer?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

Why do we use XmlSerializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.


1 Answers

This is by design. I don't know why this decision was made, but it is stated in the documentation:

  • Classes that implement ICollection or IEnumerable. Only collections are serialized, not public properties.

(Look under "Items that can be serialized" section). Someone has filed a bug against this, but it won't be changed - here, Microsoft also confirms that not including the properties for classes implementing ICollection is in fact the behaviour of XmlSerializer.

A workaround would be to either:

  • Implement IXmlSerializable and control serialization yourself.

or

  • Change MyClass so it has a public property of type List (and don't subclass it).

or

  • Use DataContractSerializer, which handles this scenario.
like image 80
driis Avatar answered Oct 24 '22 09:10

driis