C# XML反序列化与序列化

2025-06-21 03:47:58

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

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反序列化与序列化

5、添加将对象序列化成XML文件方法public stati罕铞泱殳c 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反序列化与序列化

7、对文件的序列化与反序列化测试//序列化XmlUtil.SerializerFile("./guoke.xml",list);//反序列化List<Data> tmpList = XmlUtil.DeserializeFile<List<Data>>("./guoke.xml");

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