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 必须是一一对应关系,否则可能报序列化失败的错误。

  • 相关阅读:
    书列君荐书|《福尔摩斯探案大全集》.(英)阿瑟.柯南道尔.扫描版
    anaconda同时集成Python2 和 Python3
    python 使用sqlite,ConfigParser实例
    python 爬虫爬取历年双色球开奖信息
    关于python 爬虫遇到的反盗链
    CentOS7搭建Docker私有仓库----Docker
    Ansible + shell 实现部署fastdfs+nginx 实现图片服务器并提供动态缩放功能;
    python+fastdfs+nginx实现打包下载功能
    监控生产服务器内存使用前十
    python操作MySQL--实例
  • 原文地址:https://www.cnblogs.com/lbhqq/p/8610814.html
Copyright © 2011-2022 走看看