c# - Xml Deserialize 适用于 .Net 4.5.2,与 4.6 中断:xmlns 不是预期的
问题描述
我们有一个反序列化大型 XML 文件的 C# 项目,并且在 .Net 4.5.2 上运行良好。
一旦我们将项目升级到 .Net 4.6,我们就会在 xmlserializer.Deserialize 调用中得到以下异常:
System.InvalidOperationException
HResult=0x80131509
Message=There is an error in XML document (1, 2).
Inner Exception 1:
InvalidOperationException: <AccountTransferRequest xmlns='http://at.dsh.cms.gov/exchange/1.0'> was not expected.
C#代码:
string filename = @"C:\CARES_TFS\FIPS140\Cares\Cares.Test\TestData\FFM Sync\FFMStateAidCat38.xml";
var xmlReader = new XmlTextReader(new FileStream(filename, FileMode.Open));
var xmlserializer = new XmlSerializer(typeof(AccountTransferRequestPayloadType));
var obj = xmlserializer.Deserialize(xmlReader) as AccountTransferRequestPayloadType;
我们反序列化的 C# 类是自动生成的,如下所示:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1087.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://at.dsh.cms.gov/extension/1.0")]
[System.Xml.Serialization.XmlRoot("AccountTransferRequest", IsNullable = false, Namespace = "http://at.dsh.cms.gov/exchange/1.0")]
public partial class AccountTransferRequestPayloadType : ComplexObjectType { ... }
以下是 xml 文件的第一行:
<exch:AccountTransferRequest
ext:atVersionText="2.4"
xsi:schemaLocation="http://at.dsh.cms.gov/exchange/1.0 ../XSD/XMLschemas/constraint/exchange/ExchangeModel.xsd"
xmlns:exch="http://at.dsh.cms.gov/exchange/1.0"
xmlns:ext="http://at.dsh.cms.gov/extension/1.0"
xmlns:hix-core="http://hix.cms.gov/0.1/hix-core"
xmlns:hix-ee="http://hix.cms.gov/0.1/hix-ee"
xmlns:hix-pm="http://hix.cms.gov/0.1/hix-pm"
xmlns:nc="http://niem.gov/niem/niem-core/2.0"
xmlns:s="http://niem.gov/niem/structures/2.0"
xmlns:scr="http://niem.gov/niem/domains/screening/2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
我们尝试过的事情:
1)添加:
<system.xml.serialization>
<xmlSerializer useLegacySerializerGeneration="true" />
</system.xml.serialization>
到 app.config
2) 删除 XML 文件中的命名空间和类属性
3) 删除对 4.6 版本 System.Xml.dll 的引用并添加对 4.5.2 版本 System.Xml.dll 的引用(同时将项目的其余部分留在 .Net 4.6)。这实际上有效,但不是我们想要的解决方案
解决方案
推荐阅读
- highcharts - Trying to figure out how to assign specific colors to specific data points in Highchart Pie chart
- sql-server - SQL Server dynamic SQL to query on sys tables
- html - 连续对齐具有不同尺寸的图像
- linux - Putty Search - String followed by one but not two symbols
- javascript - 将所有状态属性传递给函数,除了一个
- android - Android Emulator not starting - Application not responding
- python - 如何将表模式导出到 csv 文件中
- c# - 使用 C# microsoft bot 框架通过 Directline 包含附加参数
- r - 替换的长度为零:来自 R 中阿拉巴马州包的 auglag 函数
- c# - Azure Key Vault 机密访问间歇性地无法连接套接字异常