zoukankan      html  css  js  c++  java
  • xml序列化

            /// <summary>
            /// xml序列化
            /// </summary>
            /// <typeparam name="T">类型</typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string XmlSerialize<T>(this T obj)
            {
                if (obj == null) throw new NullReferenceException("");
    
                var settings = new XmlWriterSettings()
                {
                    OmitXmlDeclaration = true,//去掉xml声明
                    Encoding = Encoding.Default
                };
                var output = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(output, settings))
                {
                    ////去掉前缀和命名空间
                    var ns = new XmlSerializerNamespaces();
                    ns.Add(string.Empty, string.Empty);
    
                    var serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(writer, obj, ns);
                }
                return output.ToString();
            }
    
            /// <summary>
            /// xml反序列化
            /// </summary>
            /// <typeparam name="T">返回对象类型</typeparam>
            /// <param name="strXML"></param>
            /// <returns></returns>
            public static T DeserializeXml<T>(this string strXML) where T : class
            {
                try
                {
                    using (StringReader sr = new StringReader(strXML))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(T));
                        return serializer.Deserialize(sr) as T;
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            /// <summary>
            ///<![CDATA[ ]]>数据字段
            /// </summary>
            [XmlIgnore] //方式1,这里属性设置忽略
            public string HouseDetail { get; set; }
    
            [XmlElement("Housedetail")]
            public XmlNode[] CDataContent
            {
                get
                {
                    if (HouseDetail!=null)
                    {
                        return new XmlNode[]  {new XmlDocument().CreateCDataSection(HouseDetail)};
                    }
                    else
                    {
                        return null;
                    }
                }
                set
                {
                    HouseDetail =  value.First().Value;
                }
            }
    特殊字符处理
  • 相关阅读:
    Python面试题汇总
    异常处理及反射
    DOM
    socket
    python生成器、迭代器、列表 字典 集合解析、迭代器表达式
    C++繁琐的类型转换,C++小知识之四种类型转换
    C++命名空间
    C++合并exe文件,将两个合并成一个
    BERT 之后,Transformer 还会出现高光时刻吗
    App开发常见布局,流式布局讲解
  • 原文地址:https://www.cnblogs.com/xxxin/p/9352906.html
Copyright © 2011-2022 走看看