You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.5 KiB
C#

using System;
using System.IO;
using System.Xml.Serialization;
namespace GeoSigma.UCDraw
{
/// <summary>
/// Xml 帮助类,用于直接将 xml 转为对象,避免每次写不少重复代码
/// </summary>
public static class XmlHelper
{
/// <summary>
/// 将 xml 转为对象
/// </summary>
/// <param name="type">对象类型</param>
/// <param name="xml">xml字符串</param>
/// <returns>目标类对象</returns>
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);
}
}
/// <summary>
/// 序列化为 xml
/// </summary>
/// <param name="obj">对象</param>
/// <param name="overrides">overrides</param>
/// <returns>xml 字符串</returns>
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();
}
}
}
}