序列化Dictionary屬性到XML裡

來源:互聯網
上載者:User

<ComponentSettings>
<ComponentOne>
<SettingOne>SettingOneValue</SettingOne>
<SettingTwo>SettingTwoValue</SettingTwo>
</ComponentOne>
<ComponentTwo>
<AnotherSettingOne>AnotherSettingOneValue</AnotherSettingOne>
<AnotherSettingTwo>AnotherSettingTwoValue</AnotherSettingTwo>
</ComponentTwo>
</ComponentSettings>

 

Dictionary本身支援Serialization。key,value都是Serializable
不能直接xml序列化, 轉化成list再序列化

 

 

可以從Dictionary泛型類派生並實現IXmlSerializable

C# code
public class ComponentsProperties : Dictionary<string, Dictionary<string,string>>, System.Xml.Serialization.IXmlSerializable{    #region IXmlSerializable Members    public System.Xml.Schema.XmlSchema GetSchema()    {        throw new NotImplementedException();    }    public void ReadXml(System.Xml.XmlReader reader)    {        if (reader.IsEmptyElement)            return;        reader.Read();        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)        {            string key = reader.Name;            this[key] = new Dictionary<string, string>();            if (!reader.IsEmptyElement)            {                reader.ReadStartElement();                while (reader.NodeType != System.Xml.XmlNodeType.EndElement)                    this[key][reader.Name] = reader.ReadElementString();            }            reader.Read();        }    }    public void WriteXml(System.Xml.XmlWriter writer)    {        foreach (string key in this.Keys)        {            writer.WriteStartElement(key);            foreach (string key1 in this[key].Keys)                writer.WriteElementString(key1, this[key][key1]);            writer.WriteEndElement();        }    }    #endregion}

調用時候的寫法和原來是一樣的,例如:

C# code
public class TestClass{    [XmlElement("ComponentSettins")]    public ComponentsProperties Settings { get; set; }}void DoTest(){    TestClass test = new TestClass();    test.Settings = new ComponentsProperties();    test.Settings["ComponentOne"] = new Dictionary<string, string>();    test.Settings["ComponentOne"]["SettingOne"] = "SettingOneValue";    test.Settings["ComponentOne"]["SettingTwo"] = "SettingTwoValue";    test.Settings["ComponentTwo"] = new Dictionary<string, string>();    test.Settings["ComponentTwo"]["AnotherSettingOne"] = "AnotherSettingOneValue";    test.Settings["ComponentTwo"]["AnotherSettingTwo"] = "AnotherSettingTwoValue";    XmlSerializer xs = new XmlSerializer(typeof(TestClass));    FileStream fs = new FileStream(@"d:/test.xml", FileMode.Create);    xs.Serialize(fs, test);    fs.Close();}
==========================================================================view plaincopy to clipboardprint?
  1. /// <summary>  
  2.     /// 支援XML序列化的泛型 Dictionary  
  3.     /// </summary>  
  4.     /// <typeparam name="TKey"></typeparam>  
  5.     /// <typeparam name="TValue"></typeparam>  
  6.     [XmlRoot("SerializableDictionary")]  
  7.     public class SerializableDictionary<TKey, TValue>  
  8.         : Dictionary<TKey, TValue>, IXmlSerializable  
  9.     {  
  10.  
  11.         #region 建構函式  
  12.         public SerializableDictionary()  
  13.             : base()  
  14.         {  
  15.         }  
  16.         public SerializableDictionary(IDictionary<TKey, TValue> dictionary)  
  17.             : base(dictionary)  
  18.         {  
  19.         }  
  20.   
  21.         public SerializableDictionary(IEqualityComparer<TKey> comparer)  
  22.             : base(comparer)  
  23.         {  
  24.         }  
  25.   
  26.         public SerializableDictionary(int capacity)  
  27.             : base(capacity)  
  28.         {  
  29.         }  
  30.         public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)  
  31.             : base(capacity, comparer)  
  32.         {  
  33.         }  
  34.         protected SerializableDictionary(SerializationInfo info, StreamingContext context)  
  35.             : base(info, context)  
  36.         {  
  37.         }  
  38.         #endregion  
  39.         #region IXmlSerializable Members  
  40.         public System.Xml.Schema.XmlSchema GetSchema()  
  41.         {  
  42.             return null;  
  43.         }  
  44.         /// <summary>  
  45.         /// 從對象的 XML 表示形式產生該對象  
  46.         /// </summary>  
  47.         /// <param name="reader"></param>  
  48.         public void ReadXml(System.Xml.XmlReader reader)  
  49.         {  
  50.             XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));  
  51.             XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));  
  52.             bool wasEmpty = reader.IsEmptyElement;  
  53.             reader.Read();  
  54.             if (wasEmpty)  
  55.                 return;  
  56.             while (reader.NodeType != System.Xml.XmlNodeType.EndElement)  
  57.             {  
  58.                 reader.ReadStartElement("item");  
  59.                 reader.ReadStartElement("key");  
  60.                 TKey key = (TKey)keySerializer.Deserialize(reader);  
  61.                 reader.ReadEndElement();  
  62.                 reader.ReadStartElement("value");  
  63.                 TValue value = (TValue)valueSerializer.Deserialize(reader);  
  64.                 reader.ReadEndElement();  
  65.                 this.Add(key, value);  
  66.                 reader.ReadEndElement();  
  67.                 reader.MoveToContent();  
  68.             }  
  69.             reader.ReadEndElement();  
  70.         }  
  71.   
  72.         /**/  
  73.         /// <summary>  
  74.         /// 將對象轉換為其 XML 表示形式  
  75.         /// </summary>  
  76.         /// <param name="writer"></param>  
  77.         public void WriteXml(System.Xml.XmlWriter writer)  
  78.         {  
  79.             XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));  
  80.             XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));  
  81.             foreach (TKey key in this.Keys)  
  82.             {  
  83.                 writer.WriteStartElement("item");  
  84.                 writer.WriteStartElement("key");  
  85.                 keySerializer.Serialize(writer, key);  
  86.                 writer.WriteEndElement();  
  87.                 writer.WriteStartElement("value");  
  88.                 TValue value = this[key];  
  89.                 valueSerializer.Serialize(writer, value);  
  90.                 writer.WriteEndElement();  
  91.                 writer.WriteEndElement();  
  92.             }  
  93.         }  
  94.         #endregion  
  95.     }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.