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

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

我有这种格式的 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 对象时收到此错误。

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

最佳答案

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

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

关于c# - 将复杂的 XML 反序列化为 C# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9200204/

相关文章:

c# - 使用 int 作为符号有什么意义?

c# - .resx 文件或 Redis 中的语言字符串?

c# - 如何在WPF中的左侧添加一个复选框

xml - 将自定义字段添加到 paypal 模块 magento 1.9

php - 使用 PHP 反转 XML 的顺序

c# - 我可以通过代码而不是属性指定 XMLRoot 吗?

c# - 如何 XML 序列化对象列表数组?

c# - 如何在 C# Windows 窗体上生成验证码?

java - 使用 jSoup 从 XML 中的标签之间获取文本

c# - 无法将简单的 XML 解析为对象?