简体   繁体   English

c#中枚举的xml序列化

[英]Xml serialization of enum in c#

there. 那里。 I have the foloowing class definition: 我有以下类定义:

[Serializable]
public enum FilterType
{
    [XmlEnum("1")]
    Text = 1,
     [XmlEnum("2")]
    Date = 2,
     [XmlEnum("3")]
    Combo = 3,
     [XmlEnum("4")]
    Multichoice = 4
}

public class FilterValues : List<string>
{
    public FilterType Type { get; set; } 
}

[Serializable]
public struct SerializableKeyValuePair<K, V>
{
    public SerializableKeyValuePair(KeyValuePair<K, V> p)
    {
        this.key = p.Key;
        this.value = p.Value;
    }

    private K key;
    public K Key
    {
        get { return key; }
        set { key = value; }
    }

    private V value;
    public V Value
    {
        get { return this.value; }
        set { this.value = value; }
    }
}

and I can't make it to serialize the Type property in xml when I try to serialize array of SerializableKeyValuePair with key of type string and value of type FilterValues ( SerializableKeyValuePair<string, FilterValues>[] ). 当我尝试使用string类型的键和类型为FilterValues的值( SerializableKeyValuePair<string, FilterValues>[] )序列化SerializableKeyValuePair数组时,我无法使它在xml中序列化Type属性。 I got this result: 我得到了这个结果:

<?xml version="1.0" encoding="utf-16"?>  
<ArrayOfSerializableKeyValuePairOfStringFilterValues xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">    
<SerializableKeyValuePairOfStringFilterValues>      
<Key>Date</Key>     
 <Value>        <string>2012-5-16</string>      </Value>    
 </SerializableKeyValuePairOfStringFilterValues>    
 <SerializableKeyValuePairOfStringFilterValues>      
 <Key>bgName</Key>      <Value>        <string>4</string>      </Value>    
 </SerializableKeyValuePairOfStringFilterValues>  
 </ArrayOfSerializableKeyValuePairOfStringFilterValues>

Please help, I tried anything possible. 请帮忙,我尽力了。

It is related to this question: When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes 它与此问题有关: 当从List <>继承类时,XmlSerializer不会序列化其他属性

So, as pointed out in answer to that question, you have to change your FilterValues implementation in one of at least three possible ways: 因此,正如在回答该问题时所指出的那样,您必须以至少三种可能的方式之一更改FilterValues实现:

-implement IXmlSerializable
-remove inheritance from List
-use another serializer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM