using System;
using System.IO;
using System.Xml.Serialization;
namespace GeoSigma.UCDraw
{
///
/// Xml 帮助类,用于直接将 xml 转为对象,避免每次写不少重复代码
///
public static class XmlHelper
{
///
/// 将 xml 转为对象
///
/// 对象类型
/// xml字符串
/// 目标类对象
public static object Deserialize(Type type, string xml)
{
if (string.IsNullOrWhiteSpace(xml))
{
throw new ArgumentNullException(nameof(xml));
}
var serializer = new XmlSerializer(type);
using (var reader = new StringReader(xml))
{
return serializer.Deserialize(reader);
}
}
///
/// 序列化为 xml
///
/// 对象
/// overrides
/// xml 字符串
public static string Serialize(object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
var serializer = new XmlSerializer(obj.GetType());
using (var writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
}
}