XmlExtensions helper

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

static Lazy<XmlSerializerNamespaces> _ns = new Lazy<XmlSerializerNamespaces>(() =>
{
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;
}

/// <summary>
/// 反序列化XML为类实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlObj"></param>
/// <returns></returns>
public static T DeserializeXML<T>(string xmlObj)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xmlObj))
{
return (T)serializer.Deserialize(reader);
}
}

/// <summary>
/// 序列化类实例为XML
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeXML<T>(T obj)
{
using (StringWriter writer = new StringWriter())
{
new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
return writer.ToString();
}
}

/// <Summary>
/// the XML data into data sets
/// </ Summary>
the URL file /// <param name = "url" > contains XML data </ param>
public static XMLToDataSet the DataSet ( URL String)
{
the XmlTextReader Reader = null;
the DataSet the DataSet new new dataSet A = ();
the try
{
Reader the XmlTextReader new new = (URL);
DataSet.ReadXml (Reader);
}
the catch (Exception EX)
{
ex.Source string.Format + = ( . "{0}", URL);
}
the finally
{
IF (Reader = null)!
{
reader.Close ();
}
}
return dataSet A;
}
}

Guess you like

Origin www.cnblogs.com/xiaohouye/p/11455003.html