C# Xml序列化和反序列化Dictionary

做奇门对接时,extendProp字段是一个Map类型

C# 序列化xml时字典类型不支持

ExtendProp.cs

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Qimen.Api
{
    public class ExtendProp : Dictionary<string,string>,IXmlSerializable
    {

        #region 默认构造函数 + public ExtendProp()
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public ExtendProp()
            : base()
        {

        }
        #endregion

        #region 构造函数 + public ExtendProp(int capacity)
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="capacity">可包含的初始元素数</param>
        public ExtendProp(int capacity)
            : base(capacity)
        {

        }
        #endregion

        #region 构造函数 + public ExtendProp(IEqualityComparer<TKey> comparer)
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="comparer">比较键时要使用的 比较器 实现,或者为 null,以便为键类型使用默认的 比较器</param>
        public ExtendProp(IEqualityComparer<string> comparer)
            : base(comparer)
        {

        }
        #endregion

        #region 构造函数 + public ExtendProp(IDictionary<string, string> dictionary)
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dictionary">初始数据</param>
        public ExtendProp(IDictionary<string, string> dictionary)
            : base(dictionary)
        {

        }
        #endregion

        #region 构造函数 + public ExtendProp(int capacity, IEqualityComparer<TKey> comparer)
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="capacity">可包含的初始元素数</param>
        /// <param name="comparer">比较键时要使用的 比较器 实现,或者为 null,以便为键类型使用默认的 比较器</param>
        public ExtendProp(int capacity, IEqualityComparer<string> comparer)
            : base(capacity, comparer)
        {

        }
        #endregion

        #region 构造函数 + public ExtendProp(IDictionary<string, string> dictionary, IEqualityComparer<TKey> comparer)
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dictionary">初始数据</param>
        /// <param name="comparer">比较键时要使用的 比较器 实现,或者为 null,以便为键类型使用默认的 比较器</param>
        public ExtendProp(IDictionary<string, string> dictionary, IEqualityComparer<string> comparer)
            : base(dictionary, comparer)
        {

        }
        #endregion

        /// <summary>
        /// 取得概要
        /// 注:根据MSDN的文档,此方法为保留方法,一定返回 null。
        /// </summary>
        /// <returns>Xml概要</returns>
        public XmlSchema GetSchema()
        {
            return null;
        }

        /// <summary>  
        /// 从 XML 对象中反序列化生成本对象
        /// </summary>  
        /// <param name="reader">包含反序列化对象的 XmlReader 流</param>  
        public void ReadXml(XmlReader reader)
        {
            bool isEmpty = reader.IsEmptyElement;
            if (isEmpty) return;

            while(reader.NodeType != XmlNodeType.EndElement && reader.Read())
            {
                if(reader.IsStartElement())
                {
                    string key = reader.LocalName;
                    if (reader.IsEmptyElement)
                    {
                        this[key] = string.Empty;
                    }
                    else
                    {
                        this[key] = reader.ReadElementContentAsString();
                    }
                }
            }
        }

        /// <summary>  
        /// 将本对象序列化为 XML 对象
        /// </summary>  
        /// <param name="writer">待写入的 XmlWriter 对象</param>  
        public void WriteXml(XmlWriter writer)
        {
            foreach (string key in Keys)
            {
                string v = this[key];
                if (v == null) continue;

                writer.WriteStartElement(key);
                writer.WriteValue(v);
                writer.WriteEndElement();
            }
        }
    }
}

测试:

namespace Test;
class Program{
	static void Main(string[] args)
	{
		// 本地方法:序列化
		string CS<T>(T obj,string desc = "null") where T : class
		{
			using System.IO.StringWriter stringWriter = new System.IO.StringWriter();
			System.Xml.Serialization.XmlSerializer xmlSerializer = new(typeof(T));
			xmlSerializer.Serialize(stringWriter, obj);
			Console.WriteLine(desc);
			string xml = stringWriter.ToString();
			Console.WriteLine(xml);
			return xml;
		}

		// 本地方法:反序列化
		T CD<T>(string xml, string desc = "null") where T : class
		{
			using System.IO.StringReader stringReader = new System.IO.StringReader(xml);
			System.Xml.Serialization.XmlSerializer xmlSerializer = new(typeof(T));
			T result = xmlSerializer.Deserialize(stringReader) as T;
			Console.WriteLine(desc);
			return result;
		}
		
		Qimen.Api.ExtendProp prop = null;
		CS(prop,"null");
		prop = new Qimen.Api.ExtendProp();
		prop["name"] = "tom";
		prop["age"] = "22";
		prop["addr"] = null;
		string xml = CS(prop, "tom");
		prop = CD<Qimen.Api.ExtendProp>(xml, "d-tom");
		Console.WriteLine(prop["name"]);
		Console.ReadKey();
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闪耀星星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值