Skip to main content
 首页 » 编程设计

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

2024年02月23日13傻小

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