【问题标题】:How to Deserialize XML with Same Attribute Name in 2 Different Element?如何在 2 个不同元素中反序列化具有相同属性名称的 XML?
【发布时间】:2011-10-31 10:48:57
【问题描述】:

我的班级定义:

[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,我不是它的所有者。

提前致谢。

【问题讨论】:

  • 注意:[Serializable] 在这里没有任何用处

标签: c# xml xml-deserialization


【解决方案1】:

为此,您需要手动进行(反)序列化,或者您需要 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;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多