XML serialization - build a list of child elements of a certain type
I am brand new (day 2) to c# so I apologize ahead of time if my terminology is a bit off.
Consider the following XML and class models:
<Page label="Page 1.1">
<Group label="Group 1.1.1"></Group>
<Group label="Group 1.1.2"></Group>
<Text label="Text 1.1.1"></Text>
<Text label="Text 1.1.2"></Text>
</Page>
public class AbstractElementModel
{
[XmlAttributeAttribute()]
public string label;
}
[Serializable]
public class Page:AbstractElementModel
{
[XmlArrayItem(typeof(Group)),
XmlArrayItem(typeof(Text))]
public AbstractElementModel[] content;
}
(Group and Text models not shown, for this example they are blank classes extending AbstractElementModel)
I would like to be able to push any instances of Group or Text into the content list. However, when the XML document is deserialized content is null. I did notice that it works if I structure the XML as follows:
<Page label="Page 1.1">
<content>
<Group label="Group 1.1.1"></Group>
<Group label="Group 1.1.2"></Group>
<Text label="Text 1.1.1"></Text>
<Text label="Text 1.1.2"></Text>
</content>
</Page>
However, I need to be able to deseralize the XML structure as shown in the first example开发者_运维百科.
What is the best way to acomplish this?
Thanks for your time!
edit
Updated XML structure to make the problem clearer.
Use XmlElement if you don't want a wrapper element:
public class Page:AbstractElementModel
{
[XmlElement("Group", typeof(Group))]
[XmlElement("Text", typeof(Text))]
public AbstractElementModel[] content;
}
other notes:
- you don't need
[Serializable]
- public fields are generally not recommended - a property would be preferred
- IMO a list would be better than an array here
Given that you may have multipule nodes of the same type under Page this should work.
[Serializable]
public class Page:AbstractElementModel
{
[XmlArrayItem()]
public Group[] Group;
[XmlArrayItem()]
public Text[] Text;
}
精彩评论