简体   繁体   中英

Deserialize a list having extra properties with XmlSerializer

I want to deserialize the following XML...

<MyType>
    <Items>
        <ItemSum>
            <Value>3</Value>
        </ItemSum>
        <Item>
            <Value>1</Value>
        </Item>
        <Item>
            <Value>2</Value>
        </Item>
    </Items>
</MyType>

...into a type of following structure...

[XmlRoot("MyType")]
public class MyType
{
    [XmlArray("Items")]
    [XmlArrayItem("Item")]
    public CItems Items { get; set; }

    public class CItems : List<CItem>
    {
        [XmlElement("ItemSum")]
        public CItem ItemSum { get; set; }
    }

    public class CItem
    {
        [XmlElement("Value")]
        public int Value { get; set; }
    }
}

However, if I try so using C#'s XmlSerializer , the ItemSum property is always null . Any ideas what I am doing wrong?

Here it is:

public class MyType
{
    [XmlArray("Items")]
    [XmlArrayItem("ItemSum", typeof(ItemSum))]
    [XmlArrayItem("Item", typeof(SimpleItem))]
    public CItems Items { get; set; }

    public class CItems : List<Item> {}

    public class ItemSum : Item {}

    public class SimpleItem : Item {}

    public class Item
    {
        public int Value { get; set; }
    }
}

This way the ItemSum is an element of the list and you can know which is it by checking its type.

Edit: You could also make use of computed properties:

public class CItems : List<Item>
{
    [XmlIgnore]
    public ItemSum ItemSum
    {
        get { return this.OfType<ItemSum>().Single(); }
    }

    [XmlIgnore]
    public IEnumerable<SimpleItem> SimpleItems
    {
        get { return this.OfType<SimpleItem>(); }
    }
}

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