简体   繁体   English

使用属性和元素的相同名称在C#中反序列化XML-反射错误

[英]Deserialize XML in C# with the same name of attribute and element - reflection error

I have a document with this kind of structure: 我有一个具有这种结构的文档:

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

When I deserialize this document to get an instance of Page class, I always get reflection error and InvalidOperationException. 当我反序列化此文档以获取Page类的实例时,总是会得到反射错误和InvalidOperationException。 I figured out by debugging and a lot of try and error that the reason for this error is that i have the same name for a node (XMLElement) and a property (XMLAttribute), in this example the name is "header". 通过调试和大量的尝试和错误,我弄清楚了此错误的原因是我为节点(XMLElement)和属性(XMLAttribute)拥有相同的名称,在此示例中,名称为“ header”。 XML structure is not changeable in any way, so that is not the solution. XML结构不能以任何方式更改,因此这不是解决方案。 Is there a way to make it work, or do I have to add the property value later, outside of deserialization? 有什么方法可以使其起作用,还是我必须稍后在反序列化之外添加属性值?

Classes are in this form: 类的形式如下:

[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
}

use [XmlRoot("page")] to specify the name of generated xml root element instead of using [XmlType("page")] 使用[XmlRoot("page")]指定生成的xml根元素的名称,而不是使用[XmlType("page")]

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

You can try to generate classes from XML using Xsd.exe and see how it manages to solve this. 您可以尝试使用Xsd.exe从XML生成类,并查看其如何解决此问题。 Here is more info about classes generation from XML. 是有关从XML生成类的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM