XML 可选元素中列表的反序列化

XML Deserialization of a List in an optional Element

我有两个可能的 xml 需要反序列化。

没有 <UrmDevices> 节点:

<Account Id="1514478">
   <UrmDevice Id="66e24068-4ef4-4f7e-a675-a67bb8497611" FriendlyName="Device1" RegisteredTime="2018-03-13T07:54:03Z" LastUsed="2018-03-13T07:54:03Z" DeviceType=""/>
   <UrmDevice Id="9ead24cf-978c-4bbf-bd87-4e5d08c9c0d0" FriendlyName="Device2" RegisteredTime="2018-03-13T07:54:02Z" LastUsed="2018-03-13T07:54:02Z" DeviceType=""/>
</Account>

<UrmDevices>节点:

<Account Id="1514478">
   <UrmDevices>
      <UrmDevice Id="66e24068-4ef4-4f7e-a675-a67bb8497611" FriendlyName="Device1" RegisteredTime="2018-03-13T07:54:03Z" LastUsed="2018-03-13T07:54:03Z" DeviceType=""/>
      <UrmDevice Id="9ead24cf-978c-4bbf-bd87-4e5d08c9c0d0" FriendlyName="Device2" RegisteredTime="2018-03-13T07:54:02Z" LastUsed="2018-03-13T07:54:02Z" DeviceType=""/>
   </UrmDevices>
</Account>

Class 目前看起来像这样:

[XmlType(AnonymousType = true)]
[XmlRoot("Account")]
public class Account
{
    [XmlArray("UrmDevices", IsNullable = true)]
    [XmlArrayItem("UrmDevice")]
    public List<UrmDevice> UrmDevices { get; set; }

    [XmlAttribute]
    public string Id { get; set; }
}

我希望 <UrmDevices> 被忽略,因此无论 <UrmDevices> 是否存在,对象都将是 Account.UrmDevices。

到目前为止,我已经尝试了 IsNullable 属性(如上面的代码所示),this,这实际上不是一个解决方案...任何想法表示赞赏。

一个真正令人讨厌的黑客攻击可能是:

[XmlRoot("Account")]
public class Account
{
    [XmlArray("UrmDevices", IsNullable = true)]
    [XmlArrayItem("UrmDevice")]
    public List<UrmDevice> UrmDevices { get; set; }

    [XmlElement("UrmDevice")] // shadow UrmDevices with different layout
    public List<UrmDevice> EvilUrmDevices {
        get { return UrmDevices; }
        set { UrmDevices = value; }
    }

    // disable serialize of one of the two
    public bool ShouldSerializeEvilUrmDevices() { return false; }

    [XmlAttribute]
    public string Id { get; set; }
}

完全未经测试,并且...不寒而栗。