【问题标题】:Deserialize XML in C# with the same name of attribute and element - reflection error在C#中反序列化具有相同名称的属性和元素的XML - 反射错误
【发布时间】:2013-10-15 13:05:28
【问题描述】:

我有一个具有这种结构的文档:

<page name="some-name">
    <header>
        //some content
    </header>
    <section header="value">
        //some content
    </section>
</page>

当我反序列化此文档以获取 Page 类的实例时,我总是遇到反射错误和 InvalidOperationException。我通过调试和大量尝试和错误发现,此错误的原因是我的节点(XMLElement)和属性(XMLAttribute)具有相同的名称,在此示例中名称为“header”。 XML 结构不能以任何方式改变,所以这不是解决方案。有没有办法让它工作,或者我必须稍后在反序列化之外添加属性值?

类的形式如下:

[XmlType("page")]
public class Page
{
    [XmlAttribute("name")]
    public string Name { get; set }

    [XmlElement("header")]
    public Header Header { get; set }

    [XmlElement("section")]
    public Section Section { get; set }
}

[XmlType("section")]
public class Section
{
    [XmlAttribute("header")]
    public string Header { get; set }
}

[XmlType("header")]
public class Header
{
    //elements and attributes as properties
}

【问题讨论】:

    标签: c# xml serialization windows-8


    【解决方案1】:

    使用[XmlRoot("page")]指定生成的xml根元素的名称,而不是使用[XmlType("page")]

    https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute(v=vs.110).aspx

    【讨论】:

      【解决方案2】:

      您可以尝试使用Xsd.exe 从 XML 生成类,看看它是如何解决这个问题的。 Here 是关于从 XML 生成类的更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        • 2015-09-24
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        相关资源
        最近更新 更多