XmlExtensions帮助类

public static class XmlExtensions
{
static Lazy _settings = new Lazy(() =>
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = Encoding.UTF8;
settings.IndentChars = " ";
return settings;
});

static Lazy _ns = new Lazy(() =>
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
return ns;
});

public static string ToXml(this object obj)
{
string result = null;
using (var stream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (var writer = XmlWriter.Create(stream, _settings.Value))
{
serializer.Serialize(writer, obj, _ns.Value);
}
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
stream.Position = 0;
result = reader.ReadToEnd();
}
}
return result;
}

///


/// 反序列化XML为类实例
///

///
///
///
public static T DeserializeXML(string xmlObj)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xmlObj))
{
return (T)serializer.Deserialize(reader);
}
}

///


/// 序列化类实例为XML
///

///
///
///
public static string SerializeXML(T obj)
{
using (StringWriter writer = new StringWriter())
{
new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
return writer.ToString();
}
}

///


/// 将XML数据转换成数据集
///

/// 包含XML数据的文件的 URL
public static DataSet XMLToDataSet(string url)
{
XmlTextReader reader = null;
DataSet dataSet = new DataSet();
try
{
reader = new XmlTextReader(url);
dataSet.ReadXml(reader);
}
catch (Exception ex)
{
ex.Source += string.Format(".{0}", url);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return dataSet;
}
}

你可能感兴趣的:(XmlExtensions帮助类)