仿照UnityEngine.JsonUtility,进行简单的类转Xml文件,Xml文件转类封装。
namespace Frameworks
{
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public static class XmlUtility
{
public const string PATH_CONFIG = "/Config/GlobalConfig.xml";
public static T FromXmlFile<T>(string path) where T : new()
{
try
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(path);
if (!File.Exists(path))
throw new FileNotFoundException(path);
return (T)FromXmlFile(path, typeof(T), Encoding.UTF8);
}
catch (Exception) { return default(T); }
}
public static T FromXml<T>(string xml) where T : new()
{
return (T)FromXml(xml, typeof(T), Encoding.UTF8);
}
public static object FromXml(string xml, Type type, Encoding encoding)
{
try
{
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(xml)))
{
using (StreamReader sr = new StreamReader(ms, encoding))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
}
catch (Exception) { return null; }
}
public static object FromXmlFile(string path, Type type, Encoding encoding)
{
try
{
using (StreamReader sr = new StreamReader(path, encoding))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception) { return null; }
}
public static void SaveToXml(object obj, string path)
{
try
{
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(path);
string xmlStr = ToXml(obj);
int filePathLength = path.LastIndexOf('/');
string filePath = path.Remove(filePathLength, path.Length - filePathLength);
if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); }
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(xmlStr);
}
}
}
catch (Exception ex) { throw ex; }
}
public static string ToXml(object obj)
{
return ToXml(obj.GetType(), obj, Encoding.UTF8);
}
public static string ToXml(Type type, object obj, Encoding encoding)
{
Console.WriteLine(type);
try
{
if (obj == null)
throw new ArgumentNullException("obj");
XmlSerializer ser = new XmlSerializer(type);
using (MemoryStream stream = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(stream, encoding))
{
writer.Formatting = Formatting.Indented;
ser.Serialize(writer, obj);
}
string xml = encoding.GetString(stream.ToArray());
xml = xml.Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
return xml;
}
}
catch (Exception ex) { throw ex; }
}
}
}