DataContractSerializer不反序列化所有变量
问题描述:
我想反序列化一些xml,而没有用于在xml中创建对象的原始类。该类被称为ComOpcClientConfiguration。
它成功地设置ServerUrl和ServerUrlHda值,但没有其他人...
所以我问的是:我如何使这些值的其余部分得到适当设置,为什么他们不与他们合作我现在的代码。DataContractSerializer不反序列化所有变量
这里是我的反序列化代码:
的conf是代表ComClientConfiguration XML
DataContractSerializer ser = new DataContractSerializer(typeof(ComClientConfiguration), new Type[] {typeof(ComClientConfiguration), typeof(ComOpcClientConfiguration) });
ComOpcClientConfiguration config = (ComOpcClientConfiguration)ser.ReadObject(conf.CreateReader());
我不知道为什么我必须ComClientConfiguration和ComOpcClientConfiguration一个的XElement,有可能是一个更好的方式做已知的类型黑客我有。但现在这是我的。
这里是它在文件中看起来的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
}
答
数据合同序列化器是...挑剔。特别是,我想知道这里的元素顺序是否是问题。但是,它也不一定是使用XML的最佳工具。 XmlSerializer在这里可能更加健壮 - 它可以处理更好的XML范围。 DCS根本不打算用它作为主要的目标。
对于简单的XML,您甚至不需要任何属性等等。甚至可以在现有的XML上使用xsd.exe来生成匹配的c#类(分两步执行; XML-to-xsd; xsd- C#)。
答
要获得所有值,尝试硬编码的顺序(否则也许它会尝试按字母顺序排列):
[DataMember(Name = "ServerUrl", Order = 0)]
..
[DataMember(Name = "ServerName", Order = 1)]
..
[DataMember(Name = "ServerNamespaceUrl", Order = 2)]
..
[DataMember(Name = "MaxReconnectWait", Order = 3)]
..