| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- //XML读写类
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml.Serialization;
- namespace MvvmScaffoldFrame48.DLL.ConfigTools
- {
- public static class XMLReadWrite
- {
- /// <summary>
- /// 序列化对象到XML文件
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="data"></param>
- /// <param name="filePath"></param>
- /// <exception cref="InvalidOperationException"></exception>
- public static void SerializeToXml<T>(T data, string filePath)
- {
- try
- {
- var serializer = new XmlSerializer(typeof(T));
- using (var writer = new StreamWriter(filePath))
- {
- serializer.Serialize(writer, data);
- }
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException("XML serialization failed", ex);
- }
- }
- /// <summary>
- /// 序列化对象为XML字符串
- /// </summary>
- /// <typeparam name="T">对象类型</typeparam>
- /// <param name="data">要序列化的对象</param>
- /// <returns>XML字符串</returns>
- /// <exception cref="InvalidOperationException"></exception>
- public static string SerializeToString<T>(T data)
- {
- try
- {
- var serializer = new XmlSerializer(typeof(T));
- using (var writer = new StringWriter())
- {
- serializer.Serialize(writer, data);
- return writer.ToString();
- }
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException("XML serialization to string failed", ex);
- }
- }
- /// <summary>
- /// 从XML文件反序列化对象
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="filePath"></param>
- /// <returns></returns>
- /// <exception cref="InvalidOperationException"></exception>
- public static T DeserializeFromXml<T>(string filePath)
- {
- try
- {
- var serializer = new XmlSerializer(typeof(T));
- using (var reader = new StreamReader(filePath))
- {
- return (T)serializer.Deserialize(reader);
- }
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException("XML deserialization failed", ex);
- }
- }
- /// <summary>
- /// 从XML字符串反序列化对象
- /// </summary>
- /// <typeparam name="T">对象类型</typeparam>
- /// <param name="xmlString">XML字符串</param>
- /// <returns>反序列化的对象</returns>
- /// <exception cref="InvalidOperationException"></exception>
- public static T DeserializeFromString<T>(string xmlString)
- {
- try
- {
- var serializer = new XmlSerializer(typeof(T));
- using (var reader = new StringReader(xmlString))
- {
- return (T)serializer.Deserialize(reader);
- }
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException("XML deserialization from string failed", ex);
- }
- }
- }
- }
|