将具有2个不同XmlElementAttributes的xml反序列化为单个数组

本文关键字:反序列化 xml 单个 数组 XmlElementAttributes 2个 | 更新日期: 2023-09-27 18:24:22

所以这可能是一个随机的请求,但任何帮助都会得到极大的帮助!我正在处理一个XML文档,它是这样的。。。

<images>
    <image>
        <url>
            http://www.someUrl.com
        </url>
    </image>
    <bonusimage>
        <url>
            http://www.someOtherUrl.com
        </url>
    </bonusimage>
</images>

我想做的是:

[XmlArray("images")]
[XmlElementAttribute("image", Type = typeof(CustomImageClass), IsNullable = false)]
[XmlElementAttribute("bonusimage", Type = typeof(CustomImageClass), IsNullable = false)]
[XmlChoiceIdentifierAttribute("ItemsElementName")]
public CustomImageClass[] items;
[XmlElementAttribute(IsNullable = false)]
[XmlIgnoreAttribute()]
public ImageType[] ItemsElementName;

我还定义了一个枚举,如:

[XmlType(IncludeInSchema = false)]
public enum ImageType
{
    [XmlEnumAttribute("image")]
    CustomImage,
    BonusImage,
}

我试图在下面的网页上遵循第二个场景,它描述了我的问题。

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlchoiceidentifierattribute(v=vs.95).aspx

然而,运行此代码会导致以下错误:

为成员"items"指定的类型不明确。项目"bonusimage"answers"image"具有相同的类型。请考虑将XmlElementAttribute与XmlChoiceIdentifierAttribute一起使用。

很抱歉发布了这么多帖子,但我已经有一段时间了,我想尽可能多地提供信息!我想我需要第二双眼睛来帮助我看清哪里出了问题。

再次感谢!

将具有2个不同XmlElementAttributes的xml反序列化为单个数组

好的,谢谢你的输入,但不幸的是,我需要保持对象的顺序。这就是我发现的解决方案:

[XmlArray("images")]
[XmlElementAttribute(Type = typeof(Bonusimage))]
[XmlElementAttribute(Type = typeof(CustomImageClass))]
public CustomImageClass[] items;

[XmlType("bonusimage")]
public class Bonusimage: CustomImageClass
{
}
[XmlType("image")]
public class CustomImageClass
{
}
相关文章: