我有两个可能的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,这实际上并不是一个解决方案......任何想法都值得赞赏。
答案 0 :(得分:1)
一个非常讨厌的黑客可能是:
[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; }
}
完全未经测试,并且......不寒而栗。