Skip to content

C# XML 的序列化和反序列化

🏷️ C#

将自定义类型实例序列化为 XML;将 XML 反序列化为实例。

示例代码

DllConfig.cs

cs
using System.Collections.Generic;
using System.Text;

namespace ReadXML
{
    public class DllConfig
    {
        public string DllName { get; set; }
        public string NameSpaceName { get; set; }
        public string ClassName { get; set; }
        public string MethodName { get; set; }
        public List<string> Parameters { get; set; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("DllName : {0}\r\nNameSpaceName ; {1}\r\nClassName : {2}\r\nMethodName : {3}\r\n",
                DllName, NameSpaceName, ClassName, MethodName);

            for (int i = 0; i < Parameters.Count; i++)
            {
                sb.AppendFormat("Parameters[{0}] : {1}\r\n", i, Parameters[i]);
            }

            return sb.ToString();
        }
    }
}

Program.cs

cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ReadXML
{
    class Program
    {

        private static string _configFile = "DllConfig.xml";
        static void Main(string[] args)
        {
            if (!File.Exists(_configFile))
            {
                DllConfig config = new DllConfig();
                config.DllName = "CalcSample.dll";
                config.NameSpaceName = "CalcSample";
                config.ClassName = "Calc";
                config.MethodName = "Add";
                config.Parameters = new List<string>() { "1", "2" };

                List<DllConfig> configs = new List<DllConfig>();
                configs.Add(config);
                XmlHelper.XmlSerializeToFile(configs, _configFile, Encoding.UTF8);
            }

            if (File.Exists(_configFile))
            {
                StringBuilder sb = new StringBuilder();
                using (FileStream fs = new FileStream(_configFile, FileMode.Open))
                {
                    byte[] data = new byte[1024];
                    while (fs.Read(data, 0, 1024) > 0)
                    {
                        sb.Append(Encoding.UTF8.GetString(data));
                    }
                }

                List<DllConfig> configs = XmlHelper.XmlDeserializeFromFile<List<DllConfig>>(_configFile, Encoding.UTF8);
                Console.WriteLine(configs[0].ToString());
            }
            else
            {
                Console.WriteLine("配置文件不存在.");
            }
            Console.Read();
        }
    }
}

XmlHelper.cs

cs
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ReadXML
{
    public static class XmlHelper
    {
        private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
        {
            if (o == null)
                throw new ArgumentNullException("o");
            if (encoding == null)
                throw new ArgumentNullException("encoding");
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = encoding;
            settings.IndentChars = "    ";
            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, o);
                writer.Close();
            }
        }
        /// <summary>
        /// 将一个对象序列化为 XML 字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的 XML 字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializeInternal(stream, o, encoding);
                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }
        /// <summary>
        /// 将一个对象按 XML 序列化的方式写入到一个文件
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="path">保存文件路径</param>
        /// <param name="encoding">编码方式</param>
        public static void XmlSerializeToFile(object o, string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                XmlSerializeInternal(file, o, encoding);
            }
        }
        /// <summary>
        /// 从 XML 字符串中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="s">包含对象的 XML 字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize<T>(string s, Encoding encoding)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentNullException("s");
            if (encoding == null)
                throw new ArgumentNullException("encoding");
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
            {
                using (StreamReader sr = new StreamReader(ms, encoding))
                {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }
        /// <summary>
        /// 读入一个文件,并按 XML 的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            if (encoding == null)
                throw new ArgumentNullException("encoding");
            string xml = File.ReadAllText(path, encoding);
            return XmlDeserialize<T>(xml, encoding);
        }
    }
}

输出内容

DllName : CalcSample.dll
NameSpaceName ; CalcSample
ClassName : Calc
MethodName : Add
Parameters[0] : 1
Parameters[1] : 2

生成 XML 文件的内容

xml
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDllConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <DllConfig>
        <DllName>CalcSample.dll</DllName>
        <NameSpaceName>CalcSample</NameSpaceName>
        <ClassName>Calc</ClassName>
        <MethodName>Add</MethodName>
        <Parameters>
            <string>1</string>
            <string>2</string>
        </Parameters>
    </DllConfig>
</ArrayOfDllConfig>

参考