xml 反序列化处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Xml.Serialization;
using System.Xml;
using System.Text.RegularExpressions;
using System.Reflection;

   
 public class XmlHelper
    {
     /// <summary>  
        /// 反序列化xml字符为对象,默认为Utf-8编码  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="xml"></param>  
        /// <returns></returns>  
        public static T DeSerialize<T>(string xml)
            where T : new()
        {
            xml = xml.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\n", "");
            return DeSerialize<T>(xml, Encoding.UTF8);
        }

        /// <summary>  
        /// 反序列化xml字符为对象  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="xml"></param>  
        /// <param name="encoding"></param>  
        /// <returns></returns>  
        public static T DeSerialize<T>(string xml, Encoding encoding)
            where T : new()
        {
            try
            {
                var mySerializer = new XmlSerializer(typeof(T));

                using (var ms = new MemoryStream(encoding.GetBytes(xml)))
                {
                    using (var sr = new StreamReader(ms, encoding))
                    {
                        return (T)mySerializer.Deserialize(new NamespaceIgnorantXmlTextReader(sr));
                    }
                }
            }
            catch (Exception e)
            {
                return default(T);
            }

        }

   ///移除所有命名空间
    private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
      if (!xmlDocument.HasElements)
      {
        XElement xElement = new XElement(xmlDocument.Name.LocalName);
        xElement.Value = xmlDocument.Value;

        foreach (XAttribute attribute in xmlDocument.Attributes())
        xElement.Add(attribute);

        return xElement;
      }
      return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    }

 }
     
      /// <summary>  
        /// 忽略命名空间(重写xml 命名空间url 为空)
        /// </summary>    
public class NamespaceIgnorantXmlTextReader : XmlTextReader
        {
            public NamespaceIgnorantXmlTextReader(System.IO.StreamReader reader) : base(reader)
            {
            }

            public override string NamespaceURI
            {
                get { return ""; }
            }
        }

 

posted @ 2022-10-25 11:12  LieJimmy  阅读(38)  评论(0编辑  收藏  举报