4.1.1 类的序列化与反序列化(XmlSerializer)

本文介绍XML序列化和反序列化操作

本例子中被序列化的类(Devices)中有一个List,其元素类型为:DigitalInputInfo. 序列化以及反序列化都很简单:

序列化:即把类的对象输出到文件中。

StreamWriter streamWriter = new StreamWriter(filePath);

XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();

xmlSerializerNamespaces.Add("", "");

XmlSerializer xmlSerializer = new XmlSerializer(sourceObj.GetType());

xmlSerializer.Serialize(streamWriter, sourceObj, xmlSerializerNamespaces);

streamWriter.Close();

return true;

反序列化:从文件中加载生成类的对象。

StreamReader streamReader = new StreamReader(filePath);

XmlSerializer xmlSerializer = new XmlSerializer(type ?? typeof(T));

obj = xmlSerializer.Deserialize(streamReader);

streamReader.Close();

具体效果以及代码如下:

一、效果如下

生成的序列化文件打开后如下:

二、具体代码:

cs 复制代码
public static bool SaveToXml_FileName<T>(string filePath, T sourceObj)
{
    if (!string.IsNullOrEmpty(filePath) && sourceObj != null)
    {
        try
        {
            StreamWriter streamWriter = new StreamWriter(filePath);
            XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
            xmlSerializerNamespaces.Add("", "");
            XmlSerializer xmlSerializer = new XmlSerializer(sourceObj.GetType());
            xmlSerializer.Serialize(streamWriter, sourceObj, xmlSerializerNamespaces);
            streamWriter.Close();
            return true;
        }
        catch (Exception ex)
        {
            Log.Error(ex);

        }
    }
    return false;
}
cs 复制代码
public static T LoadFromXml_FileName<T>(string filePath, Type type = null)
{
    object obj = null;
    try
    {
        StreamReader streamReader = new StreamReader(filePath);
        XmlSerializer xmlSerializer = new XmlSerializer(type ?? typeof(T));
        obj = xmlSerializer.Deserialize(streamReader);
        streamReader.Close();
    }
    catch (Exception ex)
    {
        Log.Error(ex);
    }
    return (obj == null) ? default(T) : ((T)obj);
}
cs 复制代码
  public class DigitalInputInfo
  {
      private bool isOn = false;
      public int Id { get; set; } = 0;
      public string Name { get; set; } = string.Empty;
      public int IndexByte { get; set; } = 0;
      public int IndexBit { get; set; } = 0;
}
public class Devices 
{ 
	public List<DigitalInputInfo> digitalInputInfos = new List<DigitalInputInfo>();
}

main()
{
Devices    instance = new Devices();
DigitalInputInfo info1 = new DigitalInputInfo()
{
    Id = 1,
    IndexByte = 1,
    IndexBit = 1
};
DigitalInputInfo info2 = new DigitalInputInfo()
{
    Id = 2,
    IndexByte = 3,
    IndexBit = 4
};
instance.digitalInputInfos.Add(info1);
instance.digitalInputInfos.Add(info2);
instance.Save();
}
相关推荐
九英里路1 天前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
我不会起名字32212 天前
Redis 从 0 到 1(二十七):JSON 体积是 Protobuf 的 3.7 倍?3 种序列化的 Go 基准测试
redis·go·序列化·protobuf·messagepack
十五年专注C++开发14 天前
FlatBuffers: 一个高效的零拷贝二进制序列化库
c++·序列化·反序列化·flatbuffers
程序员大阳17 天前
副队长JavaScript教程(65)-详解JSON:轻量级数据交换格式
javascript·json·序列化·反序列化·stringify·parse
j7~19 天前
【ProtoBuf】(篇一)初识 ProtoBuf
运维·服务器·序列化·protobuf·protobuf的适用特点
骑着蜗牛撵大象3271 个月前
字节序、TLV 到 netlink:Linux 网络消息的编解码全链路
linux·网络·php·etl·序列化·字节序·tlv
换元不配限1 个月前
Android 接入 protobuf 实战:从 Gradle 配置到避开 R8 混淆坑
android·grpc·序列化·protobuf·protocolbuffers·二进制序列化·.proto
AIgorithmGEEK1 个月前
[Linux]从手写报头到内核套路:序列化、反序列化与自定义协议全链路
linux·运维·服务器·网络·序列化·反序列化
ShineWinsu2 个月前
对于ProtoBuffer:ProtoBuffer的介绍以及安装
linux·网络·google·协议·序列化·反序列化·protobuffer
j7~2 个月前
【Linux网络加餐】(篇六)网络版计算器(上):模板方法模式、序列化与 JSON
linux·c++·json·序列化·反序列化·网络版计算机