When serializing a custom generic collection to Xml how do I add an attribute to the generated collection element
-
08-07-2019 - |
Question
When serializing a custom generic collection to Xml how do I add an attribute to the generated collection element.
Currently I have:
<RootObject>
<Id>1</Id>
<Items>
<MyCollectionItem/>
<MyCollectionItem/>
</Items>
</RootObject>
What I need is:
<RootObject>
<Id>1</Id>
<Items Name="My collection name">
<MyCollectionItem/>
<MyCollectionItem/>
</Items>
</RootObject>
My code looks like this:
public class RootObject
{
[XmlArray()]
public MyCollection Items;
public string Id;
}
public class MyCollection : Collection<MyCollectionItem>
{
[XmlAttribute()]
public string Name;
}
Solution
This is not possible with XML Serialization unless you implement IXmlSerializable
on your collection class and implement your own serialization.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow