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

  • 相关阅读:
    Silverlight C# 游戏开发:Flyer05与什么什么进行搏斗
    Silverlight C# 游戏开发:Flyer07做一个有开始的游戏
    Silverlight C# 游戏开发:面向对象在游戏中的实例(一)
    Silverlight C# 游戏开发:面向对象在游戏中的实例(二)
    Silverlight C# 游戏开发:Flyer06小小的改进让游戏更有趣
    linux网络命令ip\route\links回顾
    Google Style的C++编码规范
    TCP/IP协议和IP组播的视频传输
    Multicast server and client in Python
    用户profile中umask码的含义详解(默认是022)
  • 原文地址:https://www.cnblogs.com/lbhqq/p/8610814.html
Copyright © 2011-2022 走看看