zoukankan      html  css  js  c++  java
  • 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 必须是一一对应关系,否则可能报序列化失败的错误。

  • 相关阅读:
    linux下自动同步internet时间
    String,StringBuffer与StringBuilder的区别
    Spring Boot CLI安装
    java中Date与String的相互转化
    MyBatis Sql语句中的转义字符
    MyBatis详解 与配置MyBatis+Spring+MySql
    MyBatis的foreach语句详解
    不可变集合 Immutable Collections
    Java日期时间使用总结
    Java将一段逗号分割的字符串转换成一个数组
  • 原文地址:https://www.cnblogs.com/lbhqq/p/8610814.html
Copyright © 2011-2022 走看看