2011-10-31 78 views
1

我的類定義:如何在2個不同元素中反序列化具有相同屬性名稱的XML?

[Serializable] 
public class MyClass 
{ 
    [XmlAttribute(AttributeName = "ID")] //Problem is here. same attr name ID. 
    public int XXX_ID { get; set; } 

    [XmlElement(ElementName = "XXX")] 
    public string XXX_Value{ get; set; } 

    [XmlAttribute(AttributeName = "ID")] //Problem is here. same attr name ID. 
    public int YYY_ID { get; set; } 

    [XmlElement(ElementName = "YYY")] 
    public string YYY_Value { get; set; } 
} 

我的XML:

<MyClass> 
    <XXX ID="123">Some Values</XXX> 
    <YYY ID="567">Some Values</YYY> 
</MyClass> 

我的問題:

我想反序列化上面的XML到對象。

在運行時期間發生錯誤,不允許在2個不同的元素中和同一根目錄下具有相同的屬性名稱。

如何解決這個問題?

P/S:我不能更改XML,我不是它的擁有者。

在此先感謝。

+0

注:'[Serializable接口]'在這裏所做的沒什麼用處 –

回答

2

爲此,您需要手動執行(反)序列化,或者您需要DTO與xml具有大致相同的佈局。例如:

public class Something { // need a name here to represent what this is! 
    [XmlAttribute] public int ID {get;set;} 
    [XmlText] public string Value {get;set;} 
} 

然後

public class MyClass { 
    public Something XXX {get;set;} 
    public Something YYY {get;set;} 
} 
相關問題