【问题标题】:Deserialize complex XML to C# object将复杂的 XML 反序列化为 C# 对象
【发布时间】:2012-03-01 07:04:08
【问题描述】:

我有这种格式的 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>

我使用 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; }
    }

反序列化的代码是 -

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();
        }

但是在反序列化时,我收到了这个错误 - 无法将类型“AreasAreaProperty[]”转换为“AreasAreaProperty” 我在创建 XMLSerializer 对象时收到此错误。

如何解决这个问题??提前谢谢..

【问题讨论】:

    标签: c# xml xml-serialization xsd xml-parsing


    【解决方案1】:

    我想我以前见过这个。 XSD.exe 并不完美,因此您需要稍微修改一下结果。在下面的代码中,在您拥有 [][] 的最后一行,删除其中一个 [],使其成为“public AreasAreaProperty[] Area...”

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

    【讨论】:

    • 谢谢。错误不再出现,但是当我检查对象 a 的值时。它仅包含最后一个区域的值。如何检索上述区域的值?
    • 你的意思是像 foreach(AreasAreaProperty a in foobar.Area) 吗?
    • @RohitVats 你有没有想过如何获得这两个区域?我正在尝试做同样的事情,但还没有做到。如果解决了请发帖。谢谢。
    【解决方案2】:

    我过去也遇到过类似的问题,看看这些问题的答案:

    如果您了解您的架构,您应该尝试将其添加到 xsd,而不是将所有内容都交给 xsd.exe 工具。

    【讨论】:

      【解决方案3】:

      你的 Deserialize() 方法的第四行不应该是

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

      而不是

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

      因为你的根元素是 .

      【讨论】:

      • 抱歉,这只是一个错字。我已经在问题中纠正了它。实际上我在方法的第一行就遇到了这个错误..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      相关资源
      最近更新 更多