2010-10-08 49 views
4

我想反序列化一些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 
} 

回答

3

數據合同序列化器是...挑剔。特別是,我想知道這裏的元素順序是否是問題。但是,它也不一定是使用XML的最佳工具。 XmlSerializer在這裏可能更加健壯 - 它可以處理更好的XML範圍。 DCS根本不打算用它作爲主要的目標。

對於簡單的XML,您甚至不需要任何屬性等等。甚至可以在現有的XML上使用xsd.exe來生成匹配的c#類(分兩步執行; XML-to-xsd; xsd- C#)。

2

要獲得所有值,嘗試硬編碼的順序(否則也許它會嘗試按字母順序排列):

[DataMember(Name = "ServerUrl", Order = 0)] 
.. 
[DataMember(Name = "ServerName", Order = 1)] 
.. 
[DataMember(Name = "ServerNamespaceUrl", Order = 2)] 
.. 
[DataMember(Name = "MaxReconnectWait", Order = 3)] 
.. 
相關問題