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

xml=xml.Trim();

序列化完毕你可以看到尾部有填充的 \0 。。。 要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")]

C# .NET XML 序列化为对象,反序列化的更多相关文章

  1. XML序列化成对象

    这个是和ALM上传测试结果结合使用的//把xml序列化成对象以及把对象序列化成xml using System; using System.Data; using System.Configurati ...

  2. Json序列化为对象方法

    /// <summary>/// json 序列化为对象/// </summary>/// <typeparam name="T">对象类型&l ...

  3. Android中序列化对象到XMl 和 XML反序列化为对象

    package com.example.xmloperation; import java.io.File; import java.io.FileOutputStream; import java. ...

  4. jackson使用问题:mapper.readValue()将JSON字符串转反序列化为对象失败或异常

    问题根源:转化目标实体类的属性要与被转JSON字符串总的字段 一 一对应!字符串里可以少字段,但绝对不能多字段. 先附上我这段出现了问题的源码: // 1.接收并转化相应的参数.需要在pom.xml中 ...

  5. C# 后台解析json,简单方法 字符串序列化为对象,取值

    如果后台是一个JSON的字符串格式如下: string str = "{\"Success\":true,\"Msg\":\"成功!\&qu ...

  6. java 使用xom对象数据序列化为xml、反序列化、Preferences相关操作小案例

    package org.rui.io.xml; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import ...

  7. 匿名对象序列化为XML

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.X ...

  8. C#操作Xml:XmlSerializer 对象的Xml序列化和反序列化

    这篇随笔对应的.Net命名空间是System.Xml.Serialization:文中的示例代码需要引用这个命名空间. 为什么要做序列化和反序列化? .Net程序执行时,对象都驻留在内存中:内存中的对 ...

  9. JSON和XML格式与对象的序列化及反序列化的辅助类

    下面的代码主要是把对象序列化为JSON格式或XML格式等 using System; using System.Collections.Generic; using System.Globalizat ...

随机推荐

  1. mac安装破解的Navicat

    原文:https://www.jianshu.com/p/f42785e55b6b 原始文档没操作成功,折腾了一下午,后来在如下地址看的简洁版的,突然发现一句重要的话,豁然开朗. 原文链接:https ...

  2. java 每间隔一段时间执行一段代码

    Java中java.util.Timer类中有若干个schedule的重载方法,其中 void schedule(TimerTask task, long delay, long period ) 安 ...

  3. Scrapy创建项目问题

    创建项目时报错 ModuleNotFoundError: No module named 'cryptography.hazmat.bindings._constant_time' pip insta ...

  4. C# array与arraylist区别及获取sql字段名

    array与arraylist的区别: 1.  Array 的容量是固定的,而 ArrayList 的容量是根据需要自动扩展的.如果更改了 ArrayList.Capacity 属性的值,则自动进行内 ...

  5. 2018-No.7-SicnuCtf

    5月份的比赛现在才有时间在博客贴出来,这是我第二次出题了,第一次是上届的初赛,这次是决赛的题. 签到(base_or_base) 解压得到两个文件小明.zip和......txt,根据文件名提示猜测是 ...

  6. select 使其默认选中文本不为空

    ```html<select ref="type" v-model="selectedvalue" > <option v-for=" ...

  7. Laravel Scout 开启队列, 自定义queue name和queue connection

    scout.php的默认配置: 'queue' => env('SCOUT_QUEUE', false), 修改为: 'queue' => [ 'queue' => env('SCO ...

  8. excel 用VBA将所有单元格内容全部转换为文本

    Sub 将所有列全部转换为文本() t=timer 'Cells(Rows.Count, 1).End(xlUp).Row 获取第一列最后一个非空单元格的行号 s = Cells(, Columns. ...

  9. mysql免安装版的下载与安装

    下载 打开:https://www.mysql.com/downloads/ 1.点击该项:

  10. 解决Ubuntu19.04下网易云音乐打不开的问题

    Ubuntu19.04下打开网易云音乐的v18.04版会出现以下错误: opt/netease/netease-cloud-music/netease-cloud-music: symbol look ...