gpt4 book ai didi

c# - DataContractSerializer 不反序列化所有变量

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

我试图在没有用于在 xml 中创建对象的原始类的情况下反序列化一些 xml。该类称为 ComOpcClientConfiguration。
它成功地设置了 ServerUrl 和 ServerUrlHda 值,但没有设置其余值...
所以我要问的是:我怎样才能正确设置这些值的其余部分,为什么它们不能使用我当前的代码。

这是我的反序列化代码:
conf 是一个 XElement,代表 ComClientConfiguration xml

DataContractSerializer ser = new DataContractSerializer(typeof(ComClientConfiguration), new Type[] {typeof(ComClientConfiguration), typeof(ComOpcClientConfiguration) });
ComOpcClientConfiguration config = (ComOpcClientConfiguration)ser.ReadObject(conf.CreateReader());

我不知道为什么我必须有 ComClientConfiguration 和 ComOpcClientConfiguration,可能有更好的方法来解决我所拥有的已知类型。但现在这就是我所拥有的。

这是文件中的 xml。

<ComClientConfiguration  xsi:type="ComOpcClientConfiguration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ServerUrl>The url</ServerUrl>
<ServerName>a server name </ServerName>
<ServerNamespaceUrl>a namespace url</ServerNamespaceUrl>
<MaxReconnectWait>5000</MaxReconnectWait>
<MaxReconnectAttempts>0</MaxReconnectAttempts>
<FastBrowsing>true</FastBrowsing>
<ItemIdEqualToName>true</ItemIdEqualToName>
<ServerUrlHda>hda url</ServerUrlHda>
</ComClientConfiguration>

这是我构建的要反序列化的类:

[DataContract(Name = "ComClientConfiguration", Namespace = "http://opcfoundation.org/UA/SDK/COMInterop")]
public class ComClientConfiguration
{
public ComClientConfiguration() { }

//Prog-ID for DA-connection
[DataMember(Name = "ServerUrl"), OptionalField]
public string ServerUrl;//url
[DataMember(Name = "ServerName")]
public string ServerName;
[DataMember(Name = "ServerNamespaceUrl")]
public string ServerNamespaceUrl;//url
[DataMember(Name = "MaxReconnectWait")]
public int MaxReconnectWait;
[DataMember(Name = "MaxReconnectAttempts")]
public int MaxReconnectAttempts;
[DataMember(Name = "FastBrowsing")]
public bool FastBrowsing;
[DataMember(Name = "ItemIdEqualToName")]
public bool ItemIdEqualToName;

//ProgID for DA-connection
[DataMember, OptionalField]
public string ServerUrlHda;//url
}

我还必须制作这门课,它是相同的,但名称不同。用于 Serializer 中的已知类型,因为我不确切知道整个类型命名的工作原理。

[DataContract(Name = "ComOpcClientConfiguration", Namespace = "http://opcfoundation.org/UA/SDK/COMInterop")]
public class ComOpcClientConfiguration
{
public ComOpcClientConfiguration() { }

... Same innards as ComClientConfiguration
}

最佳答案

Data-contract-serializer 是……挑剔的。特别是,我想知道是否简单的元素顺序是这里的问题。但是,它也不一定是处理 XML 的最佳工具。 XmlSerializer 在这里可能更强大——它可以处理范围更广的 XML。 DCS 根本不打算用于此,因为它是主要目标。

对于简单的 XML,您通常甚至不需要任何属性等。您甚至可以在现有 XML 上使用 xsd.exe 来生成匹配的 c# 类(分两步;XML-to-xsd;xsd-to-c# ).

关于c# - DataContractSerializer 不反序列化所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3893152/

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