Xml 序列化列表节点上的获取属性

Xml serialize get attribute on list node

我目前有这样的结构

[XmlRoot("command")]
public class Command
{
    [XmlArray("itemlist")]
    [XmlArrayItem("item")]
    public List<Item> Items { get; set; }
}

[XmlRoot("item")]
public class Item
{
    [XmlAttribute("itemid")]
    public string ItemID { get; set; }
}

这很适合它的目的,但考虑到这一点 xml

<command>
    <itemlist totalsize="999">
        <item itemid="1">
        <item itemid="2">
        ...
    </itemlist>
</command>

如何在反序列化时从 itemlist 中获取 totalsize? XML 是我收到的,不是我能控制的。
我不是在寻找 GetAttributeValue 或类似的东西,而是纯粹使用 xmlserializer

您需要将 itemlistitem 拆分为两个 类。

[XmlRoot("command")]
public class Command
{
    [XmlElement("itemlist")]
    public ItemList ItemList { get; set; }
}

public class ItemList
{
    [XmlAttribute("totalsize")]
    public int TotalSize { get; set; }

    [XmlElement("item")]
    public List<Item> Items { get; set; }
}

public class Item
{
    [XmlAttribute("itemid")]
    public string ItemID { get; set; }
}

顺便说一句,请注意 XmlRoot 属性仅与 root 元素相关。在这种情况下,您在 Item 上的那个将被忽略。