简体   繁体   中英

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM