C# XML反序列化与序列化

2025-10-06 18:14:35

1、首先我们建一个XmlUtil类,然后,提供四个方法,对字符串和文件进入反序列化与序列化

C# XML反序列化与序列化

2、添加 将XML字符串反序列化成对象 方法肥蹲

public static T Deserialize<T>(string xml, string xmlRootName = "Root")

{

    T result = default(T);

    using (StringReader sr = new StringReader(xml))

    {

        XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?

            new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName));

 裕鬼泪       result = (T)xmlSerializer.Deserialize(sr);

    }

    return result;

}

C# XML反序列化与序列化

3、添加  将XML文件反序列化成对象 方法

public static T DeserializeFile<T>(string filePath, string xmlRootName = "Root")

{

    T result = default(T);

    if (File.Exists(filePath))

    {

        using (StreamReader reader = new StreamReader(filePath))

        {

           获阅 XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?

                new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName));

            result = (T)xmlSerializer.Deserialize(reader);

        }

    }

    return result;

}

C# XML反序列化与序列化

4、添加 将对象序列化成XML字符串 方法

public static string Serializer(object sourceObj, string xmlRootName = "Root")

{

    MemoryStream Stream = new MemoryStream();

    Type type = sourceObj.GetType();

    XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?

        new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName));

    xmlSerializer.Serialize(Stream, sourceObj);

    Stream.Position = 0;

    StreamReader sr = new StreamReader(Stream);

    string str = sr.ReadToEnd();

    sr.Dispose();

    Stream.Dispose();

    return str;

}

C# XML反序列化与序列化

5、添加 将对象序列化成XML文件 方法

public static void SerializerFile(string filePath, object sourceObj, string xmlRootName = "Root")

{

    if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)

    {

        Type type = sourceObj.GetType();

        using (StreamWriter writer = new StreamWriter(filePath))

        {

            XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?

                new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName));

            xmlSerializer.Serialize(writer, sourceObj);

        }

    }

}

C# XML反序列化与序列化

6、对字符串的序列化与反序列化测试

// 序列化

string strTmp = XmlUtil.Serializer(data);

// 反序列化

Data tmpData = XmlUtil.Deserialize<Data>(strTmp);

C# XML反序列化与序列化

7、对文件的序列化与反序列化测试

// 序列化

XmlUtil.SerializerFile("./guoke.xml",list);

// 反序列化

List<Data> tmpList = XmlUtil.DeserializeFile<List<Data>>("./guoke.xml");

C# XML反序列化与序列化

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢