2011-10-31 42 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;} 
} 
相关问题