using System;
|
using System.IO;
|
using System.Reflection;
|
using System.Xml;
|
using System.Xml.Serialization;
|
|
namespace UtilLib
|
{
|
public static class XmlHelper
|
{
|
|
static readonly XmlSerializerNamespaces DEFAULT_NS = new XmlSerializerNamespaces();
|
|
static XmlHelper()
|
{
|
DEFAULT_NS.Add("", "");
|
}
|
|
/// <summary>
|
/// serialize object to xml file.
|
/// </summary>
|
/// <param name="path">the path to save the xml file</param>
|
/// <param name="obj">the object you want to serialize</param>
|
public static void SerializeToXml(string path, object obj)
|
{
|
XmlSerializer serializer = new XmlSerializer(obj.GetType());
|
string content = string.Empty;
|
//serialize
|
using (StringWriter writer = new StringWriter())
|
{
|
serializer.Serialize(writer, obj, DEFAULT_NS);
|
content = writer.ToString();
|
}
|
//save to file
|
using (StreamWriter stream_writer = new StreamWriter(path))
|
{
|
stream_writer.Write(content);
|
}
|
}
|
|
/// <summary>
|
/// xml 文件反序列化为对象
|
/// </summary>
|
/// <typeparam name="T">序列化类型</typeparam>
|
/// <param name="path">the path of the xml file</param>
|
/// <returns>对象</returns>
|
public static T DeserializeFromXml<T>(string path)
|
{
|
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
using (StreamReader reader = new StreamReader(path))
|
{
|
return (T)serializer.Deserialize(reader);
|
}
|
}
|
public static bool ReadFromXml<T>(T obj, string path)
|
{
|
XmlDocument xd = new XmlDocument();
|
xd.Load(path);
|
|
Type type = typeof(T);
|
XmlNode root = xd.SelectSingleNode(type.Name);
|
if (root == null)
|
{
|
return false;
|
}
|
|
//获取 RefHero 中所有的实例私有字段
|
FieldInfo[] fieldArray = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
|
foreach (FieldInfo filed in fieldArray)
|
{
|
string fileName = filed.Name;
|
XmlNode node = root.SelectSingleNode(fileName);
|
if (node == null)
|
{
|
continue;
|
}
|
filed.SetValue(obj, node.InnerText);
|
}
|
return true;
|
}
|
|
public static T DeepClone<T>(T data)
|
{
|
using (MemoryStream stream = new MemoryStream())
|
{
|
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
serializer.Serialize(stream, data);
|
stream.Seek(0, SeekOrigin.Begin);
|
return (T)serializer.Deserialize(stream);
|
}
|
}
|
}
|
}
|