简体   繁体   English

将复杂的XML反序列化为C#对象

[英]Deserialize complex XML to C# object

I have XML in this format - 我有这种格式的XML-

<Areas>
  <Area>
    <Property Name="Test11">a1</Property>
    <Property Name="Test12">a2</Property>
    <Property Name="Test13">a3</Property>
    <Property Name="Test14">a4</Property>
    <Property Name="Test15">a5</Property>
  </Area>
  <Area>
    <Property Name="Test21">b1</Property>
    <Property Name="Test22">b2</Property>
    <Property Name="Test23">b3</Property>
    <Property Name="Test24">b4</Property>
    <Property Name="Test25">b5</Property>
  </Area>
</Areas>

I generated the class using xsd.exe provided by Microsoft as - 我使用Microsoft提供的xsd.exe生成了此类-

[Serializable()]
    public partial class Areas
    {
        [XmlArrayItem("Property", typeof(AreasAreaProperty))]
        public AreasAreaProperty[][] Area { get; set; }
    }

    [Serializable()]
    public partial class AreasAreaProperty
    {
        [XmlAttribute()]
        public string Name { get; set; }

        [XmlText()]
        public string Value { get; set; }
    }

Code for deserializing is - 反序列化的代码是-

private void Deserialize()
        {
            XmlSerializer xs = new XmlSerializer(typeof(Areas));
            FileStream fs = new FileStream("XMLFile1.xml", FileMode.Open);
            XmlReader xr = new XmlTextReader(fs);
            Areas a = (Areas)xs.Deserialize(xr);
            fs.Close();
        }

But at the time of deserilaization, i am getting this error - Cannot convert type 'AreasAreaProperty[]' to 'AreasAreaProperty' I am getting this error at the time of creation of object of XMLSerializer. 但是在反序列化时,我遇到了此错误- 无法将类型'AreasAreaProperty []'转换为'AreasAreaProperty'我在创建XMLSerializer对象时遇到了此错误。

How to solve this issue?? 如何解决这个问题? Thanks in advance.. 提前致谢..

I think I've seen this before. 我想我以前看过。 XSD.exe isn't perfect and so you need to tinker with the results a little bit. XSD.exe并不完美,因此您需要对结果进行一些修改。 In the following code, on the last line where you have the [][], remove one of the [] so that it's "public AreasAreaProperty[] Area..." 在下面的代码中,在具有[] []的最后一行上,删除[]之一,使其为“ public AreasAreaProperty [] Area ...”。

[Serializable()]
public partial class Areas
{
    [XmlArrayItem("Property", typeof(AreasAreaProperty))]
    public AreasAreaProperty[][] Area { get; set; }

I've had similar troubles in the past, have a look at the answers to these: 过去我也遇到过类似的麻烦,请看一下这些问题的答案:

If you have knowledge about your schema you should try and add it to the xsd and not leave everything up to the xsd.exe tool. 如果您了解架构,则应尝试将其添加到xsd中,而不要将所有内容留给xsd.exe工具。

Shouldn't the fourth line of your Deserialize() method be Deserialize()方法的第四行不应该是

    Areas a = (Areas)xs.Deserialize(xr); 

instead of 代替

    Area a = (Area)xs.Deserialize(xr); 

since your root element is . 因为您的根元素是。

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

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