Net Core教程

C#|xml 在原有文档增加一个序列化类

本文主要是介绍C#|xml 在原有文档增加一个序列化类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在原有的xml基础上添加一个序列化类。

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Sex { get; set; }

    [XmlElement("Dog")]
    public List<Dog> Dog { get; set; }

    public string Good { get; set; } = "100";
    private string valuePrivate { get; set; } = "0";
}

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
}   

XmlSerializerHelper

class XmlSerializerHelper
{
    public void XmlSerial(object obj, string xmlFile)
    {
        // 序列化
        using (MemoryStream ms = new MemoryStream())
        {
            XmlWriterSettings setting = new XmlWriterSettings() {
                Encoding = new UTF8Encoding(false),
                Indent = true,
            };
            using (XmlWriter writer = XmlWriter.Create(ms, setting))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                // 去掉命名空间
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // 命名空间赋值为空
                xmlSerializer.Serialize(writer, obj, ns);

                // 用StreamWriter 
                string xmlContent = Encoding.UTF8.GetString(ms.ToArray()); // 转成字符转
                StreamWriter streamWriter = new StreamWriter(xmlFile);
                streamWriter.Write(xmlContent);
                streamWriter.Close();
            }
        }
    }

    public XElement XmlSerial(object obj)
    {
        // 序列化
        using (MemoryStream ms = new MemoryStream())
        {
            XmlWriterSettings setting = new XmlWriterSettings() {
                Encoding = new UTF8Encoding(false),
                Indent = true,
            };
            using (XmlWriter writer = XmlWriter.Create(ms, setting))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                // 去掉命名空间
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // 命名空间赋值为空
                xmlSerializer.Serialize(writer, obj, ns);

                ms.Position = 0;  // 把流的位置弄到最前面,不然找不到根元素
                
                XDocument objElem = XDocument.Load(ms);
                XElement rootElem = objElem.Root;
                // 可以直接加载
                // XElement rootElem = XElement.Load(ms);
                return rootElem;
            }
        }
    }

    // 返序列化
    public T XmlDeserial<T>(T obj, string xmlFile)
    {
        // 用 MemoryStream
        string xmlString = File.ReadAllText(xmlFile); // xml 内容提取出来
        using (MemoryStream MS = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
        {
            using (XmlReader xr = XmlReader.Create(MS))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                obj = (T)xmlSerializer.Deserialize(xr);  // 不要误写为 MS 流,有这个重载不会报错。但运行有错。
            }
        }

        return obj;
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Dog> dogs = new List<Dog> {
            new Dog() { Name = "小黑", Age = 9 },
            new Dog() { Name = "小黄", Age = 10 }
        };

        Person person = new Person() {
            Name = "孙悟空",
            Age = 500,
            Sex = "男",
            Dog = dogs
        };

        XmlSerializerHelper xmlSerializerHelper = new XmlSerializerHelper();
        xmlSerializerHelper.XmlSerial(person, "Person.xml");

        // 增加一个 Dog 类
        XElement rootElem = XElement.Load("Person.xml");
        rootElem.Add(xmlSerializerHelper.XmlSerial(new Dog() { Name = "小辉", Age = 15 }));
        rootElem.Save("Person.xml");

        Console.ReadKey();
    }
}

输出:

<?xml version="1.0" encoding="utf-8"?>
<Person>
  <Name>孙悟空</Name>
  <Age>500</Age>
  <Sex>男</Sex>
  <Dog>
    <Name>小黑</Name>
    <Age>9</Age>
  </Dog>
  <Dog>
    <Name>小黄</Name>
    <Age>10</Age>
  </Dog>
  <Good>100</Good>
  <Dog>
    <Name>小辉</Name>
    <Age>15</Age>
  </Dog>
</Person>

看后面添加了一个 Dog 小辉。

注意两种添加根元素的方式:

ms.Position = 0;  // 把流的位置弄到最前面,不然找不到根元素

XDocument objElem = XDocument.Load(ms);
XElement rootElem = objElem.Root;
// 可以直接加载,找到根元素
XElement rootElem = XElement.Load(ms);
这篇关于C#|xml 在原有文档增加一个序列化类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!