Attribute is not serialized by XmlSerializer

I would like to serialize the class in XML by assigning it an XML attribute. Excerpt:

[XmlType(TypeName = "classmy")] public class MyClass2 : List<object> { [XmlAttribute(AttributeName = "myattr")] public string Name { get; set; } } public class MyConst { public MyConst() { MyClass2 myClass2 = new MyClass2 { 10, "abc" }; myClass2.Name = "nomm"; XmlSerializer serializer = new XmlSerializer(typeof(MyClass2)); serializer.Serialize(Console.Out, myClass2); } } 

But the resulting XML looks like this:

 <?xml version="1.0" encoding="IBM437"?> <classmy xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <anyType xsi:type="xsd:int">10</anyType> <anyType xsi:type="xsd:string">abc</anyType> </classmy> 

All is well and good, except that myClass2.Name is not serialized. I was expecting something on the line

 <classmy myattr="nomm" [...]>[...]</classmy> 

... Why is it not serialized and how can it be?

+7
source share
3 answers

dont get List<T> , create a class with List element

 [XmlType(TypeName = "classmy")] public class MyClass2 { [XmlAttribute(AttributeName = "Items")] List<object> Items { get; set; } //need to change type in `<>` [XmlAttribute(AttributeName = "myattr")] public string Name { get; set; } } 
+4
source

Alternative solution: use an array instead of a list and XmlElement

  [XmlType(TypeName = "classmy")] public class MyClass2 { [XmlElement(ElementName = "Items")] public object[] Items { get; set; } [XmlAttribute(AttributeName = "myattr")] public string Name { get; set; } } 
+1
source

XmlSerializer processes List <> in a special way:

XmlSerializer can handle classes that implement IEnumerable or ICollection differently if they meet certain requirements. A class that implements IEnumerable must implement the public Add method, which takes one parameter. The Add method parameter must be consistent (polymorphic) with the type returned from the IEnumerator.Current property returned from the GetEnumerator method. A class that implements ICollection in addition to IEnumerable (e.g. CollectionBase) must have a public property Item indexed (an index in C #) that accepts an integer and must have a public Count property of type integer. The parameter passed to the Add method must be of the same type as that returned from the Item property or one of these types. For classes that implement ICollection, the values ​​to be serialized will be retrieved from the indexed Item property, rather than by calling GetEnumerator. Also note that public fields and properties will not be serialized, except for public fields that return another collection class (one that implements ICollection) . MSDN - Scroll through XML Serialization

That's why it only serialized your class as a list of objects, without your property. A better solution is to enable the List as class public property and mark it as an XmlElement.

+1
source

All Articles