4

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

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

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
}

我还必须做这门课,它是一样的,但名字不同。用于序列化程序中的已知类型,因为我不确切知道整个类型命名的工作原理。

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

    ... Same innards as ComClientConfiguration
}
4

2 回答 2

3

数据合同序列化器是......挑剔。特别是,我想知道这里的问题是否只是元素顺序。但是,它也不一定是使用 XML 的最佳工具。XmlSerializer 在这里可能更健壮 - 它可以处理更好的 XML 范围。DCS 根本不打算将其作为主要目标。

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

于 2010-10-08T21:08:57.577 回答
2

要获取所有值,请尝试对顺序进行硬编码(否则可能会尝试按字母顺序):

[DataMember(Name = "ServerUrl", Order = 0)]
..
[DataMember(Name = "ServerName", Order = 1)]
..
[DataMember(Name = "ServerNamespaceUrl", Order = 2)]
..
[DataMember(Name = "MaxReconnectWait", Order = 3)]
..
于 2014-04-18T12:40:25.527 回答