gpt4 book ai didi

c# - 由于 XML 节点的顺序不正确,DataContract 反序列化失败

转载 作者:数据小太阳 更新时间:2023-10-29 01:45:21 25 4
gpt4 key购买 nike

我对 DataContractSerializer 的行为感到困惑。我们的配置是基于 XML 的。 XML 用作 DataContractSerializer.ReadObject 方法的源。最近遇到反序列化对象的某些属性没有设置的问题。我跟踪了更改并发现这些属性是手动添加到 XML 中的。我认为这是可以的。显然这在 DataContractSerializer 的意见中是不正确的,因为它似乎期望 XML 节点按字母顺序排序。真的?!反序列化看起来真的很简单——顺序读取 XML,解析节点名称,设置相应的属性。订购的目的是什么?

有解决办法吗?也许是 DataContractSerializer 的某种设置?

最佳答案

我最近遇到了这个问题。为了解决这个问题,我使用了 XmlSerializer 并从 XmlElement 属性中删除了显式排序:

set proxy_tool="C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SvcUtil.exe" /nologo /t:code /ser:XmlSerializer /UseSerializerForFaults
set sed_tool="$(ProjectDir)sed.exe" -r -i "s/,?[[:space:]]*Order=[[:digit:]]+//"

%proxy_tool% /o:"Proxy1.cs" /n:*,Namespaces.Name1 "Proxy1.wsdl"
%sed_tool% "Proxy1.cs"

%proxy_tool% /o:"Proxy2.cs" /n:*,Namespaces.Name2 "Proxy2.wsdl"
%sed_tool% "Proxy2.cs"

...

有一些 more information on my blog post .

如果您想知道顺序为何重要,那是因为 XSD 中的 sequence 具有定义的顺序,并且 Web 服务契约(Contract)是使用 XSD 定义的。

来自 the specification :

The consequence of this definition is that any element appearing in an instance whose type is declared to be USAddress (e.g. shipTo in po.xml) must consist of five elements and one attribute. These elements must be called name, street, city, state and zip as specified by the values of the declarations' name attributes, and the elements must appear in the same sequence (order) in which they are declared.

关于c# - 由于 XML 节点的顺序不正确,DataContract 反序列化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9796187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com