C# 之对象与Xml序列化工具类

写在前面

一个常用的对象与Xml序列化工具类,使用系统类库System.Xml,序列化时需要注意只能将对象的公共字段和读/写属性转换为 XML。不转换方法、索引器、私有字段或只读属性。另外XmlSerializer 类无法序列化ArrayList数组和List<T>数组。

using System.Xml.Serialization;

代码实现

cs 复制代码
    public class ObjectSerializer<T> where T : class
    {
        public void SerializeToXml(string filePath, object target)
        {
            var dir = Path.GetDirectoryName(Path.GetFullPath(filePath));
            if (string.IsNullOrWhiteSpace(dir) || !Directory.Exists(dir))
                throw new Exception("File Path Invalid");

            using (var writer = new StreamWriter(filePath))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(writer, target);
            }
        }

        public string SerializeToXml(T target)
        {
            using (var writer = new StringWriter())
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(writer, target);
                return writer.ToString();
            }
        }

        public T DeserializeFromString(string xml)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (StringReader sr = new StringReader(xml))
            {
                return xmlSerializer.Deserialize(sr) as T;
            }
        }

        public T DeserializeFromXml(string filePath)
        {
            if (!File.Exists(filePath))
                throw new Exception("File Path Invalid");

            try
            {
                using (var reader = new StreamReader(filePath))
                {
                    var xmlSerializer = new XmlSerializer(typeof(T));
                    return (T)xmlSerializer.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
相关推荐
rockey6275 小时前
AScript正式推出Template模板引擎
c#
沐言Agent7 小时前
做工业上位机,这个 C# 开源框架把 PLC 通讯、流程控制和 MES 对接都备好了
c#·工业上位机
投研帮16 小时前
C#文档管理系统开发实战:技术选型、全文检索与并发控制
c#·.net·文档管理系统
2395730491 天前
在 Avalonia 12 上用纯 .NET 重写 Monaco 编辑器:TKCode.Arc CodeEditor / DiffEditor / LSP 深度架构与实战
c#·.net·lsp·avalonia·monaco·codeeditor·tkcode.arc
新*2 天前
在 .NET 里嵌入 IronPython:内存只涨不降的真相与正确的封装姿势
c#·.net·内存优化·ironpython·dlr
2501_930707782 天前
使用C#从 PowerPoint 演示文稿中提取图片
开发语言·c#·powerpoint
zhanghaha13142 天前
C# 系列教程_15 类 Class 保姆级系统教程(面向新手,大量示例 + 底层机理)
java·开发语言·c#
Risehuxyc3 天前
HttpClient怎么传POST参数
c#
zdr尽职尽责6 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
BruceNeter8 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net