using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
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 (TextWriter 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>
|
/// <returns></returns>
|
public static string FileOutput(T obj)
|
{
|
var xml = string.Empty;
|
try
|
{
|
using (MemoryStream ms = new MemoryStream())
|
{
|
var setting = new XmlWriterSettings()
|
{
|
Encoding = new UTF8Encoding(false),
|
Indent = true,
|
};
|
using (XmlWriter writer = XmlWriter.Create(ms, setting))
|
{
|
XmlSerializer xmlSearializer = new XmlSerializer(obj.GetType());
|
xmlSearializer.Serialize(writer, obj);
|
xml= Encoding.UTF8.GetString(ms.ToArray());
|
}
|
}
|
}
|
catch (Exception)
|
{
|
LogHelper.Error("报表Json文件格式化失败! ");
|
}
|
return xml;
|
}
|
|
/// <summary>
|
/// 保存对象到xml文件中
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="fileName"></param>
|
/// <param name="t"></param>
|
public static void SaveObjectXmlFile<T>(string fileName, T t) where T : class
|
{
|
var str = XmlHelper<T>.FileOutput(t);
|
UTF8Encoding utf8 = new UTF8Encoding(false);
|
File.WriteAllText(fileName, str, utf8);
|
}
|
|
|
}
|
}
|