C# .NET XML 序列化为对象,反序列化

如果遇到:   根级别上的数据无效。 行 1,位置 1   。;即无法反序列化(反序列失败),得到对象为null ,把 xml 文本 Trim一下。

xml=xml.Trim(); 

 序列化完毕你可以看到尾部有填充的 。。。 要Trim掉。  参考:https://www.cnblogs.com/XChWaad/p/3346875.html

你可以TRIM 前后观察下Length. 有不可见空格

xml.Length
328

xml=xml.Trim();

xml.Length
327

XML SAMPLE:

<xml>


<bank_type><![CDATA[CFT]]></bank_type>
<cash_fee><![CDATA[1]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[Y]]></is_subscribe>

<nonce_str><![CDATA[74971f5846d34fe0a35b8f636413f0e4]]></nonce_str>


<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[C46252FFBA5F10F39F7A040F3BC5D58D]]></sign>

<sub_is_subscribe><![CDATA[N]]></sub_is_subscribe>

<time_end><![CDATA[20190417113750]]></time_end>
<total_fee>1</total_fee>
<trade_type><![CDATA[JSAPI]]></trade_type>

</xml>

--

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace SixunWxPayApi
{
    public class XmlSerializerUtil
    {
         

        public static T Deserialize<T>( string xml)
        {
      xml = xml.Trim(); //避免有不可见空格字符,导致无法反序列化            
      Type type
=typeof(T); try { using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(type); return (T)xmldes.Deserialize(sr); } } catch (Exception e) { // System.Diagnostics.Debug.WriteLine("ERROR " + e.StackTrace); return default(T); } } //where T : class public static string XmlSerializer<T>(T serialObject) { XmlSerializer ser = new XmlSerializer(typeof(T)); System.IO.MemoryStream mem = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8); // 强制指定命名空间,覆盖默认的命名空间 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); ser.Serialize(writer, serialObject, namespaces); writer.Close();

        string rst= Encoding.UTF8.GetString(mem.ToArray());
        rst = rst.Trim();//避免有不可见空格字符


        return rst;


        }

    }
}

--

实体类要加声明:

[XmlRootAttribute("xml", Namespace = "", IsNullable = false)]

调用:  

WxResultBaseModel wrbm = XmlSerializerUtil.Deserialize<WxResultBaseModel>(strreturn);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace SixunWxPayApi
{
    /// <summary>
    /// 微信返回数据基础model,XML根元素是"xml"
    /// </summary>
   [XmlRootAttribute("xml", Namespace = "", IsNullable = false)]
    public class WxResultBaseModel
    {
        public string result_code { get; set; }
        public string return_code { get; set; }

        public string sign { get; set; }


        public string mch_id { get; set; }

        public string sub_mch_id { get; set; }

        public string out_trade_no { get; set; }

        public string transaction_id { get; set; }

        public string trade_state { get; set; }

        public string total_fee { get; set; }
       

    }
}

--

//如果是数组,一定要指明XmlElement
[XmlElement("bankAccountVo")]

原文地址:https://www.cnblogs.com/runliuv/p/10740093.html