欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#对XML文件的序列化和反序列化

程序员文章站 2022-03-01 12:38:18
...

     

using System.Xml.Serialization;

public class XMLOperate
{
    public static void SerialXml<T>(T t, string path)
    {
        using (FileStream finfo = new FileStream(path, FileMode.Create))
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");  //去除声明
            XmlSerializer se = new XmlSerializer(typeof(T));
            se.Serialize(finfo, t, ns);
        }
    }

    public static T DeserialXml<T>(string path)
    {
        using (FileStream stream = new FileStream(path, FileMode.Open))
        {
            XmlSerializer se = new XmlSerializer(typeof(T));
            return (T)se.Deserialize(stream);
        }
    }
}


 

相关标签: C# C#