c# 中xml序列化时相同节点存入不同类型值

先上需要序列话的类定义:

    [System.Xml.Serialization.XmlIncludeAttribute(typeof(DescriptionType))]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.2612.0")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.tempuri.org/OTA/2003/05")]
    public partial class ParagraphType {
    private object[] itemsField;
        private ItemsChoiceType[] itemsElementNameField;
/// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Image", typeof(string))] [System.Xml.Serialization.XmlElementAttribute("ListItem", typeof(ParagraphTypeListItem))] [System.Xml.Serialization.XmlElementAttribute("Text", typeof(FormattedTextTextType))] [System.Xml.Serialization.XmlElementAttribute("URL", typeof(string), DataType="anyURI")] [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")] public object[] Items { get { return this.itemsField; } set { this.itemsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] [System.Xml.Serialization.XmlIgnoreAttribute()] public ItemsChoiceType[] ItemsElementName { get { return this.itemsElementNameField; } set { this.itemsElementNameField = value; } }
  }

其中Items为object类型,可动态存放4种节点:Image  ListItem Text URL,类型也是对应各自类型(如Image是string)。

需要注意的是XmlChoiceIdentifierAttribute方法用来通过枚举进一步检测成语,因此例子中的枚举类型是ItemsElementName,定义如下:

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.2612.0")]
    [System.SerializableAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.tempuri.org/OTA/2003/05", IncludeInSchema=false)]
    public enum ItemsChoiceType {
        
        /// <remarks/>
        Image,
        
        /// <remarks/>
        ListItem,
        
        /// <remarks/>
        Text,
        
        /// <remarks/>
        URL,
    }

定义完毕,当序列化时,只需同时将Items和ItemsElementName 赋值如下:

Items = new List<object>()
  {
    new FormattedTextTextType() { Value = "备注一"},
    "stringssssss",
  }.ToArray(),
ItemsElementName = new ItemsChoiceType[]{ ItemsChoiceType.Text, ItemsChoiceType.Image}

此处同时使用了两个类型的数据,反序列化时只要认清顺序就能成功得到各自的结果。

最后需要注意的是,Items 与ItemsElementName 必须是一一对应关系,否则可能报序列化失败的错误。

posted @ 2018-03-20 17:26  好人卡收藏家  阅读(1243)  评论(0编辑  收藏  举报