I’m trying to create a class which I can serialize to produce the following XML:
<chart palette='1'> <categories> <category label='2001' /> <category label='2002' />
..etc
I have a class which look something like this:
[XmlRoot('chart')] public class Chart { [XmlAttributeAttribute('palette')] public string Palette; [XmlElement('categories')] public List<Category> Categories = new List<Category>(); } [XmlRoot('category')] public class Category { [XmlAttributeAttribute('label')] public string Label; }
However, this does not produce the desired chart->categories->category@label structure. The XmlRoot on the Category class doesn’t seem to be used. Here is the output I have from that code:
<chart palette='2'> <categories label='2002' /> </chart>
How can I get the XML structure I want?
Use XmlArrayAttribute and XmlArrayItemAttribute
Sometimes is can be useful to just create the xml structure you want, and then use xsd.exe to generate classes from it. This has to be done in a 2-step process, first generating an xsd file, and then classes from that.
This will probably not give the exact result you want (unless you have a really good xsd, and don’t just generate it from the xml), but does give some ideas