0
点赞
收藏
分享

微信扫一扫

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

Aliven888 2022-04-13 阅读 60
xml序列化

做奇门对接时,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 条评论