C#中XML的序列化与反序列化使用

前言

正如前面提到,程序配置信息的保存,除了有Json、Ini外,还有一种文件格式是比较好的,那就是XML数据格式,它的可读可写性也是比较友好的,C#也为其提供了解析类库,开发者只需要根据实际业务场景进行选择对应函数即可。

1、写数组类型的结构

代码:

        public void SerializeCalib(string name)
        {
            var calib = new para_calib_t()
            {
                R = new float[9] { 0.9997641F, 0, 0.0217155F, 0.01682982F, 0.6319438F, -0.7748315F, -0.01372297F, 0.7750143F, 0.6317948F },
                T = new float[3] { 11, 22, 33 },
                ksr_inv = new float[9] { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                plane = new float[4] { 1.1F, (float)2.1, (float)3.1, (float)4.1 },
                dir = new float[3] { (float)1.2, (float)2.2, (float)3.2 },
                dist = new float[5] { (float)1.3, (float)2.3, (float)3.3, (float)4.3, (float)5.3 }
            };

            FileStream stream = File.OpenWrite(name);
            using (TextWriter writer = new StreamWriter(stream))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(para_calib_t));
                serializer.Serialize(writer, calib);
            }
        }

效果:

2、读取数组类型的XML文件

代码:

 private void ReadCalibPara(string name)
        {
            para_calib_t para;
            using (var stream = new FileStream(name, FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(para_calib_t));
                para = (para_calib_t)serializer.Deserialize(stream);
            }
        }

效果:

3、写普通类型的结构

代码:

 //把一个对象序列化为xml
        public  void SerializeProduct(string name)
        {
            //new products object
            var product = new Para
            {
                ProductID = 200,
                CategoryID = 100,
                Discontinued = false,
                ProductName = "Serialize Objects",
                QuantityPerUnit = "6",
                ReorderLevel = 1,
                SupplierID = 1,
                UnitPrice = 1000,
                UnitsInStock = 10,
                UnitsOnOrder = 0
            };

            FileStream stream = File.OpenWrite(name);
            using (TextWriter writer = new StreamWriter(stream))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Para));
                serializer.Serialize(writer, product);
            }
        }

效果:

4、读取文件至对象

代码:

Product product;
            using (var stream = new FileStream(name, FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(Product));
                product = serializer.Deserialize(stream) as Product;
            }

效果:

5、通过XmlWriter写文件

代码:

public static void WriterSample(string filename)
        {
            var settings = new XmlWriterSettings
            {
                Indent = true,
                NewLineOnAttributes = true,
                Encoding = Encoding.UTF8,
                WriteEndDocumentOnClose = true
            };

            StreamWriter stream = File.CreateText(filename);
            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                writer.WriteStartDocument();
                //Start creating elements and attributes
                writer.WriteStartElement("book");
                writer.WriteAttributeString("genre", "Mystery");
                writer.WriteAttributeString("publicationdate", "2001");
                writer.WriteAttributeString("ISBN", "123456789");
                writer.WriteElementString("title", "Case of the Missing Cookie");
                writer.WriteStartElement("author");
                writer.WriteElementString("name", "Cookie Monster");
                writer.WriteEndElement();
                writer.WriteElementString("price", "9.99");
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }

效果:

6、使用XmlAttributeOverrides写文件

代码:

        
        public  void SerializeInventory(string name)
        {
            var product = new Product
            {
                ProductID = 100,
                ProductName = "Product Thing",
                SupplierID = 10
            };

            var book = new BookProduct
            {
                ProductID = 101,
                ProductName = "How To Use Your New Product Thing",
                SupplierID = 10,
                ISBN = "1234567890"
            };

            Product[] products = { product, book };
            var inventory = new Inventory
            {
                InventoryItems = products
            };

            using (FileStream stream = File.Create(name))
            {
                var serializer = new XmlSerializer(typeof(Inventory), GetInventoryXmlAttributes());
                serializer.Serialize(stream, inventory);
            }
        }

        public XmlAttributeOverrides GetInventoryXmlAttributes()
        {
            var inventoryAttributes = new XmlAttributes();
            inventoryAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute("Book", typeof(BookProduct)));
            inventoryAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute("Product", typeof(Product)));

            var bookIsbnAttributes = new XmlAttributes();
            bookIsbnAttributes.XmlAttribute = new XmlAttributeAttribute("Isbn");

            var productDiscountAttributes = new XmlAttributes();
            productDiscountAttributes.XmlAttribute = new XmlAttributeAttribute("Discount");

            var overrides = new XmlAttributeOverrides();

            overrides.Add(typeof(Inventory), "InventoryItems", inventoryAttributes);

            overrides.Add(typeof(BookProduct), "ISBN", bookIsbnAttributes);
            overrides.Add(typeof(Product), "Discount", productDiscountAttributes);
            return overrides;
        }

效果:

7、XML帮助类

internal class XmlSerializeHelper
    {
        //对象转XML
        public static string ObjToXml(object obj)
        {
            using (MemoryStream Stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(obj.GetType());
                xml.Serialize(Stream, obj);
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                string str = sr.ReadToEnd();
                return str;
            }
        }

        /// <summary>
        /// 实体对象序列化成xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            string str = string.Empty;
            using (MemoryStream Stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(obj.GetType());
                xml.Serialize(Stream, obj);
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                str = sr.ReadToEnd();

                str = str.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
                str = str.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
            }
            return str;
        }

        /// <summary>
        /// 反序列化xml字符为对象,默认为Utf-8编码
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string xml)
            where T : new()
        {
            return DeSerialize<T>(xml, Encoding.UTF8);
        }

        /// <summary>
        /// 反序列化xml字符为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string xml, Encoding encoding)
            where T : new()
        {
            var mySerializer = new XmlSerializer(typeof(T));
            using (var ms = new MemoryStream(encoding.GetBytes(xml)))
            {
                using (var sr = new StreamReader(ms, encoding))
                {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }
    }

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值