using System;
|
using System.IO;
|
using System.Text;
|
using System.Xml;
|
using System.Xml.Serialization;
|
|
|
namespace IStation.Application
|
{
|
/// <summary>
|
///
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
public class XmlHelper<T> where T : class
|
{
|
/// <summary>
|
/// 对象生成Xml文档
|
/// </summary>
|
public string ObjectToXml(T obj)
|
{
|
using (StringWriter writer = new StringWriter())
|
{
|
XmlSerializer serializer = new XmlSerializer(obj.GetType());
|
serializer.Serialize(writer, obj);
|
return writer.ToString();
|
}
|
}
|
|
|
/// <summary>
|
/// xml文档生成类
|
/// </summary>
|
public T XmlToObject(string xmlStr)
|
{
|
try
|
{
|
using (StringReader reader = new StringReader(xmlStr))
|
{
|
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
return serializer.Deserialize(reader) as T;
|
}
|
}
|
catch (Exception ex)
|
{
|
var a = ex.Message;
|
return null;
|
}
|
}
|
|
|
/// <summary>
|
/// 保存对象到xml文件中
|
/// </summary>
|
public static void SaveObjectXmlFile<T>(string fileName, T t) where T : class
|
{
|
var str = new XmlHelper<T>().ObjectToXml(t);
|
File.WriteAllText(fileName, str, Encoding.UTF8);
|
}
|
|
|
}
|
}
|