可以使用XmlSerializer直接序列化和反序列化xml

反序列化如以下代码
        private T? XmlDeseriallize<T>(string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var xmlReader = System.Xml.XmlReader.Create(fileStream);
                var deserializedObject = (T?)serializer.Deserialize(xmlReader);
                return deserializedObject;
            }
        }
调用方法
var udidEntity = XmlDeseriallize<udid>(filePath)
其中,xml文件内容示例:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<udid version="1.0">
    <header frequency="daily" id="20240520235039" type="DELTA_INCREMENTAL">
        <downloadFilePart>1</downloadFilePart>
        <downloadFileTotalParts>1</downloadFileTotalParts>
        <numberRkeyecordXML>3480</numberRkeyecordXML>
        <numberRecordsDatabase>3480</numberRecordsDatabase>
        <creationDate>2024-05-20 23:50:39</creationDate>
    </header>
    <devices>
        <device>
            <zxxsdycpbs>06974652782710</zxxsdycpbs>
            <cpbsbmtxmc>GS1</cpbsbmtxmc>
            <cpbsfbrq>2024-05-20</cpbsfbrq>
            <zxxsdyzsydydsl>1</zxxsdyzsydydsl>
            <sydycpbs></sydycpbs>
            <bszt>一维码</bszt>
            <sfyzcbayz>是</sfyzcbayz>
            <zcbacpbs></zcbacpbs>
            <sfybtzjbs>否</sfybtzjbs>
            <btcpbsyzxxsdycpbssfyz></btcpbsyzxxsdycpbssfyz>
            <btcpbs></btcpbs>
            <cpmctymc>一次性使用吸引活检针及附件</cpmctymc>
            <spmc></spmc>
            <ggxh>CLA2505</ggxh>
            <sfwblztlcp>否</sfwblztlcp>
            <cpms>吸引活检针25G×50mm</cpms>
            <cphhhbh>202710</cphhhbh>
            <yflbm></yflbm>
            <qxlb>器械</qxlb>
            <flbm>14-01-09</flbm>
            <tyshxydm>91430300MA4RGKD89R</tyshxydm>
            <zczbhhzbapzbh>湘械注准20222141907</zczbhhzbapzbh>
            <ylqxzcrbarmc>湖南省拓川医疗科技有限公司</ylqxzcrbarmc>
            <ylqxzcrbarywmc></ylqxzcrbarywmc>
            <ybbm>C01060200700003149010000032</ybbm>
            <cplb>耗材</cplb>
            <cgzmraqxgxx>说明书或标签上面不包含MR安全性信息</cgzmraqxgxx>
            <sfbjwycxsy>是</sfbjwycxsy>
            <zdcfsycs></zdcfsycs>
            <sfwwjbz>是</sfwwjbz>
            <syqsfxyjxmj>否</syqsfxyjxmj>
            <mjfs></mjfs>
            <qtxxdwzlj></qtxxdwzlj>
            <tsrq></tsrq>
            <scbssfbhph>是</scbssfbhph>
            <scbssfbhxlh>否</scbssfbhxlh>
            <scbssfbhscrq>是</scbssfbhscrq>
            <scbssfbhsxrq>是</scbssfbhsxrq>
            <tscchcztj>本产品应贮存在通风良好、无腐蚀性气体、清洁的环境内。储存温度范围为0℃至30℃,相对湿度不超过85%。本产品应使用无腐蚀性气体、对产品无污染的运输工具运输,严禁日晒雨淋,搬运时应注意防止包装破损。</tscchcztj>
            <tsccsm></tsccsm>
            <deviceRecordKey>069746527827102024042904331816</deviceRecordKey>
            <versionNumber>1</versionNumber>
            <versionTime>2024-05-20</versionTime>
            <versionStauts>新增</versionStauts>
            <correctionNumber>0</correctionNumber>
            <correctionRemark></correctionRemark>
            <correctionTime></correctionTime>
        </device>
        <device>
            <zxxsdycpbs>06931450103406</zxxsdycpbs>
            <cpbsbmtxmc>GS1</cpbsbmtxmc>
            <cpbsfbrq>2024-05-20</cpbsfbrq>
            <zxxsdyzsydydsl>1</zxxsdyzsydydsl>
            <sydycpbs></sydycpbs>
            <bszt>一维码,二维码,RFID</bszt>
            <sfyzcbayz>是</sfyzcbayz>
            <zcbacpbs></zcbacpbs>
            <sfybtzjbs>否</sfybtzjbs>
            <btcpbsyzxxsdycpbssfyz></btcpbsyzxxsdycpbssfyz>
            <btcpbs></btcpbs>
            <cpmctymc>定制式活动义齿</cpmctymc>
            <spmc></spmc>
            <ggxh>钴铬钼支架可摘全口义齿 1402040900</ggxh>
            <sfwblztlcp>否</sfwblztlcp>
            <cpms>由合成树脂牙、卡环、树脂基托及连接体组成</cpms>
            <cphhhbh></cphhhbh>
            <yflbm></yflbm>
            <qxlb>器械</qxlb>
            <flbm>17-06-04</flbm>
            <tyshxydm>91441900675189913A</tyshxydm>
            <zczbhhzbapzbh>粤械注准20152171212</zczbhhzbapzbh>
            <ylqxzcrbarmc>东莞市帕菲克义齿科技有限公司</ylqxzcrbarmc>
            <ylqxzcrbarywmc></ylqxzcrbarywmc>
            <ybbm></ybbm>
            <cplb>耗材</cplb>
            <cgzmraqxgxx>说明书或标签上面不包含MR安全性信息</cgzmraqxgxx>
            <sfbjwycxsy>否</sfbjwycxsy>
            <zdcfsycs></zdcfsycs>
            <sfwwjbz>否</sfwwjbz>
            <syqsfxyjxmj>否</syqsfxyjxmj>
            <mjfs></mjfs>
            <qtxxdwzlj></qtxxdwzlj>
            <tsrq></tsrq>
            <scbssfbhph>是</scbssfbhph>
            <scbssfbhxlh>是</scbssfbhxlh>
            <scbssfbhscrq>是</scbssfbhscrq>
            <scbssfbhsxrq>否</scbssfbhsxrq>
            <tscchcztj></tscchcztj>
            <tsccsm></tsccsm>
            <deviceRecordKey>0693145010340620240518045505448</deviceRecordKey>
            <versionNumber>1</versionNumber>
            <versionTime>2024-05-20</versionTime>
            <versionStauts>新增</versionStauts>
            <correctionNumber>0</correctionNumber>
            <correctionRemark></correctionRemark>
            <correctionTime></correctionTime>
            <contactList>
                <contact>
                    <qylxrcz></qylxrcz>
                    <qylxryx>2074662804@qq.com</qylxryx>
                    <qylxrdh>0769-85160532</qylxrdh>
                </contact>
            </contactList>
        </device>
    </devices>
</udid>
C# 类型示例:
    //为从XML反序列化来而做准备
    public class udid
    {
        public header header { get; set; } = new();
        [XmlArrayItem("device")]//序列化反序列化时,当DeviceInfoDto对应的xml中元素的名字不是DeviceInfoDto而是device时,用该特性指定类型DeviceInfoDto对应的在xml中的元素的名字device。如果不这么做,则需要变能,改以下代码中List<DeviceInfoDto>为List<device>其中device为一个继承自DeviceInfoDto类型的子类
        public List<DeviceInfoDto> devices { get; set; } = new();
    }
    public class header
    {
        [XmlAttribute("frequency")]
        public string Frequency { get; set; } = string.Empty;
        [XmlAttribute("id")]
        public string Id { get; set; } = string.Empty;
        [XmlAttribute("type")]
        public string Type { get; set; } = string.Empty;
        public int downloadFilePart { get; set; }
        public int downloadFileTotalParts { get; set; }
        public int numberRkeyecordXML { get; set; }
        public int numberRecordsDatabase { get; set; }

        #region 当直接使用一个类型为Datetime属性名为creationDate来在反序列化xml文件中的日期时间类型的接收者时,反序列化会报错:【字符串“2020-07-31 09:29:16”不是有效的AllXsd值】。于是采入引入一个中间属性stringCreationDate(类型为string)和存储其值的字段_creationDate(类型为DateTime)的方式,运行过程1.当反序列化时从xml文件读取元素名为creationDate的元素值并通过stringCreationDate的set访问器将其值在转值为DateTime类型后存放于字段_creationDate中 2.当C#代码中其他地方要访问这个值时,就从creationDate属性的get访问器传递出_creationDate字段的值。缺点:需引入不必要的属性和字段,而且属性名还必须是public的,这会让外部访问者对这个中间属性感到疑惑。
        private DateTime _creationDate;
        [XmlElement(ElementName = "creationDate")]
        public string stringCreationDate { get => _creationDate.ToString("yyyy-MM-dd HH:mm:ss"); set => _creationDate = Convert.ToDateTime(value); }
        [XmlIgnore]
        public DateTime creationDate { get => _creationDate; }
        #endregion
    }


    public class DeviceInfoDto
    {

        [XmlElement("cpmctymc")]//用来在做xml反序列化时,指定本属性对应到xml文件中的标签的名字。(注意还有一个是XmlAttribute它是指对应到xml标签的属性名字)
        public string CPMCTYMC { get; set; }

        [XmlElement("spmc")]
        public string SPMC { get; set; }

        [XmlElement("ggxh")]
        public string GGXH { get; set; }

        [XmlElement("cpms")]
        public string CPMS { get; set; }

        [XmlElement("tyshxydm")]
        public string TYSHXYDM { get; set; }

        [XmlElement("flbm")]
        public string CategoryCode { get; set; }

        [XmlElement("deviceRecordKey")]
        public string deviceRecordKey { get; set; }

        [XmlElement("versionTime")]
        public DateTime versionTime { get; set; }

        [XmlElement("zxxsdycpbs")]
        public string DI { get; set; }

        [XmlElement("cpbsbmtxmc")]
        public string DeviceCodeType { get; set; }

        [XmlElement("ylqxzcrbarmc")]
        public string Manufacturer { get; set; }

        [XmlElement("ylqxzcrbarywmc")]
        public string EnManufacturer { get; set; }

        [XmlElement("zczbhhzbapzbh")]
        public string RegistrationCertificateNo { get; set; }

        [XmlElement("versionStauts")]
        public string versionStauts { get; set; }
    }

注意其中几个关键点

1. 读取xml文件时,以独占方式,这样可以避免文件被别的程序打开时读取报错的问题。

using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {}

2. 在序列化反序列化时,当类型DeviceInfoDto对应的xml中元素的名字不是DeviceInfoDto而是device时,有两种解决方法:

方法一:
用该特性[XmlArrayItem("device")]指定类型DeviceInfoDto对应的在xml中的元素的名字device。

        [XmlArrayItem("device")]
        public List<DeviceInfoDto> devices { get; set; } = new();

方法二:
需要变通:改以下代码中List<DeviceInfoDto>List<device>其中device为一个继承自DeviceInfoDto类型的子类
public List<device> devices { get; set; } = new();

public class device:DeviceInfoDto
{
}

3. 反序列化时对应C#类型DateTime时的报错处理

当直接使用一个类型为Datetime属性名为creationDate来在反序列化xml文件中的日期时间类型的接收者时,反序列化会报错:【字符串“2020-07-31 09:29:16”不是有效的AllXsd值】。于是采入引入一个中间属性stringCreationDate(类型为string)和存储其值的字段_creationDate(类型为DateTime)的方式,运行过程1.当反序列化时从xml文件读取元素名为creationDate的元素值并通过stringCreationDate的set访问器将其值在转值为DateTime类型后存放于字段_creationDate中 2.当C#代码中其他地方要访问这个值时,就从creationDate属性的get访问器传递出_creationDate字段的值。缺点:需引入不必要的属性和字段,而且属性名还必须是public的,这会让外部访问者对这个中间属性感到疑惑。

        private DateTime _creationDate;
        [XmlElement(ElementName = "creationDate")]
        public string stringCreationDate { get => _creationDate.ToString("yyyy-MM-dd HH:mm:ss"); set => _creationDate = Convert.ToDateTime(value); }
        [XmlIgnore]
        public DateTime creationDate { get => _creationDate; }

4. 序列化反序列化时,XmlSerializer可识别的常用的C#特性标签 Attribute

a. [XmlRoot("udid")]
用于C#类名上,用于指明根类型对应的xml中的元素名
b. [XmlElement("creationDate")]
用于C#属性或字段上,用于指明属性对应的xml元素名或者叫标签名为 creationDate
c. [XmlAttribute("frequency")]
用于C#属性或字段上,用于指明属性或字段对应的XML元素的属性名为 frequency
d. [XmlIgnore]
用于C#属性或字段上,用来标记该字段在序列化反序列化XML文档时是要忽略的C#属性或字段
e. [XmlArrayItem("device")]
用于C# List<T>集合类型的属性或字段上,用来标记集合中的元素类型T在XML文档中对应的元素名称

更多参考:

https://www.cnblogs.com/guogangj/p/7489218.html

posted on 2024-05-27 15:19  hrx521  阅读(74)  评论(0编辑  收藏  举报