2012-02-08 51 views
1

我有XML这种格式 -反序列化复杂的XML到C#对象

<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对象时收到此错误。

如何解决这个问题?由于事先..

回答

3

我想我以前见过这个。 XSD.exe并不完美,因此您需要稍微修改一下结果。在下面的代码,在最后一行,你有[] [],删除的[],直到它的“公共AreasAreaProperty []区......”

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

谢谢。错误不再来,但当我检查对象a的值。它仅包含最后一个区域的值。如何检索以上区域的值? – 2012-02-08 20:11:43

+0

你的意思是类似 foreach(AreasAreaProperty a在foobar.Area) ? – 2012-02-09 16:38:38

+0

@RohitVats你有没有想过如何得到两个区的?我试图做同样的事情,还没有得到它。如果你解决了它,请发布。谢谢。 – CodeChops 2014-02-14 00:23:59

0

不应您的反序列化()方法的第四行是

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

代替

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

因为你的根元素是。

+0

Sory,这只是一个错字。我在问题中纠正了它。其实我在这种方法的第一行得到这个错误.. – 2012-02-08 19:56:30