zoukankan      html  css  js  c++  java
  • .net core XML 解析帮助类

        public class XSerializer
        {
            /// <summary>
            /// 将对象序列化为xml字符串
            /// </summary>
            /// <typeparam name="T">类型<peparam>
            /// <param name="t">对象</param>
            public static string ObjectToXml<T>(T t) where T : class
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add(string.Empty, string.Empty);
                    formatter.Serialize(stream, t, namespaces);
                    string result = Encoding.UTF8.GetString(stream.ToArray());
                    return result;
                }
            }
            /// <summary>
            /// 序列化成XML 清空格式
            /// </summary>
            public static string ObjectToXml<T>(T t, Encoding encoding) where T : class
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                using MemoryStream stream = new MemoryStream();
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);
                XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, encoding);
                xmlTextWriter.Formatting = System.Xml.Formatting.None;
                formatter.Serialize(xmlTextWriter, t, namespaces);
                xmlTextWriter.Flush();
                xmlTextWriter.Close();
                string result = encoding.GetString(stream.ToArray());
                return result;
            }
    
            /// <summary>
            /// 字符串转换为对象
            /// </summary>
            public static T XmlToObject<T>(string xml) where T : class
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
                {
                    T result = formatter.Deserialize(ms) as T;
                    return result;
                }
            }
        }
    
  • 相关阅读:
    屠呦呦团队研究新进展:青蒿中有其他抗疟成分
    lammps模拟化学反应(1)
    伪类的使用--鼠标悬浮效果
    bootstrap中模态框的使用
    idea_2018.1.5版本的激活使用
    火狐浏览器开发者版本
    使用bootstrap的相关配置
    StringBuffer类
    如何判断字符串中大写字母,小写字母和数字出现的次数??
    ssm框架结构的搭建
  • 原文地址:https://www.cnblogs.com/rsls/p/14851990.html
Copyright © 2011-2022 走看看