2012-02-08 54 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