【问题标题】:Xml serialize get attribute on list nodeXML序列化获取列表节点上的属性
【发布时间】:2025-12-19 17:45:11
【问题描述】:

我目前有这样的结构

[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

【问题讨论】:

  • 你需要在Command类中添加一个类似于Item类中ItemID属性的属性。
  • 提示:复制您的 xml,进入 Visual Studio 并选择 编辑 > 选择性粘贴 > 将 XML 粘贴为类。虽然名称映射您应该手动进行

标签: c# xmlserializer


【解决方案1】:

您需要将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 上的那个会被忽略。

【讨论】:

  • 我想了这么多,但希望我不需要为了容纳额外的总大小而再上一堂课。