序列化Dictionary属性到XML里

2 篇文章 0 订阅

<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(); }

==========================================================================
  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.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`XmlSerializer`是.NET中用于XML序列化和反序列化的类,但它无法直接序列化`Dictionary`字典对象。这是因为`Dictionary`类在.NET中不是可序列化的类型。 `XmlSerializer`可以序列化和反序列化具有公共可读/可写属性的类和结构,以及数组和集合类型。但是,在序列化过程中,它无法处理键/值对的字典结构。 要序列化字典对象,你可以使用其他方法,例如将字典转换为可序列化的类型,或使用其他序列化库(如`DataContractSerializer`或`Json.NET`)。 如果你仍然希望使用`XmlSerializer`来序列化字典,你可以考虑创建一个可序列化的封装类来存储字典的键和值,并在需要时将其转换为字典。以下是一个示例代码: ```csharp using System; using System.Collections.Generic; using System.Xml.Serialization; public class SerializableDictionary<TKey, TValue> { [XmlArrayItem("Item")] public List<SerializableKeyValuePair<TKey, TValue>> Items { get; set; } public SerializableDictionary() { Items = new List<SerializableKeyValuePair<TKey, TValue>>(); } public SerializableDictionary(Dictionary<TKey, TValue> dictionary) { Items = new List<SerializableKeyValuePair<TKey, TValue>>(); foreach (var kvp in dictionary) { Items.Add(new SerializableKeyValuePair<TKey, TValue>(kvp.Key, kvp.Value)); } } public Dictionary<TKey, TValue> ToDictionary() { var dictionary = new Dictionary<TKey, TValue>(); foreach (var item in Items) { dictionary[item.Key] = item.Value; } return dictionary; } } public class SerializableKeyValuePair<TKey, TValue> { [XmlAttribute("Key")] public TKey Key { get; set; } [XmlAttribute("Value")] public TValue Value { get; set; } public SerializableKeyValuePair() { } public SerializableKeyValuePair(TKey key, TValue value) { Key = key; Value = value; } } public class Program { public static void Main() { // 创建一个字典 Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("Apple", 1); dictionary.Add("Banana", 2); dictionary.Add("Orange", 3); // 将字典转换为可序列化的类型 var serializableDictionary = new SerializableDictionary<string, int>(dictionary); // 创建XmlSerializer对象并序列化字典 XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, int>)); using (var writer = new System.IO.StringWriter()) { serializer.Serialize(writer, serializableDictionary); string xml = writer.ToString(); Console.WriteLine(xml); } } } ``` 上述代码中,我们创建了一个`SerializableDictionary`类,它包含一个`Items`属性,用于存储字典的键值对。然后,我们将字典转换为`SerializableDictionary`对象,并使用`XmlSerializer`将其序列化XML字符串。 希望这个示例可以帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值