• XmlExtensions帮助类


    public static class XmlExtensions
    {
    static Lazy<XmlWriterSettings> _settings = new Lazy<XmlWriterSettings>(() =>
    {
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.NewLineChars = " ";
    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>
    /// 将XML数据转换成数据集
    /// </summary>
    /// <param name="url">包含XML数据的文件的 URL</param>
    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;
    }
    }

  • 相关阅读:
    java动态注册Filter,Servlet,Listener
    java防止html脚本注入
    java中常用的几种跨域方式
    backbone 要点知识整理
    创建对象-constructor丢失的问题
    css3 动画(animation)-简单入门
    sass安装
    sass安装步骤
    javascript how sort() work
    javascript 获取调用属性的对象
  • 原文地址:https://www.cnblogs.com/xiaohouye/p/11455003.html
Copyright © 2020-2023  润新知