2013-10-09 72 views
1

我有下面的代碼,但無法反序列化,你能看到我要去哪裏錯了嗎?它只捕獲第一個數組項目上的第一條記錄。無法反序列化XML

[XmlRootAttribute("Booking")] 
     public class Reservation 
     { 
      [XmlArray("Included")] 
      [XmlArrayItem("Meals")] 
      public Meals[] Food { get; set; } 

      [XmlArrayItem("Drinks")] 
      public Drinks[] Drink { get; set; } 

     } 

     public class Meals 
     { 
      [XmlAttribute("Breakfast")] 
      public string Breakfast { get; set; } 

      [XmlAttribute("Lunch")] 
      public string Lunch { get; set; } 

      [XmlAttribute("Dinner")] 
      public string Dinner { get; set; } 
     } 

     public class Drinks 
     { 
      [XmlAttribute("Soft")] 
      public string Softs { get; set; } 

      [XmlAttribute("Beer")] 
      public string Beer { get; set; } 

      [XmlAttribute("Wine")] 
      public string Wine { get; set; } 
     } 

下面是相關的XML

<?xml version="1.0" standalone="yes"?> 
<Booking> 
    <Included> 
     <Meals 
     Breakfast="True" 
     Lunch="True" 
     Dinner="False"> 
     </Meals> 
     <Drinks 
      Soft="True" 
      Beer="False" 
      Wine="False"> 
     </Drinks> 
    </Included> 
    <Included> 
     <Meals 
     Breakfast="True" 
     Lunch="False" 
     Dinner="False"> 
     </Meals> 
     <Drinks 
      Soft="True" 
      Beer="True" 
      Wine="True"> 
     </Drinks> 
    </Included> 
</Booking> 

我有點新手的所以任何幫助將是巨大的,通過多次exmaples你已經在網上我還沒有去過拖網後不幸能夠弄清楚這一點。

回答

0

使用下面的例子,在ListItem陣列應用此語法,

[XmlType("device_list")] 
[Serializable] 
public class DeviceList { 
    [XmlAttribute] 
    public string type { get; set; } 

    [XmlElement("item")] 
    public ListItem[] items { get; set; } 
} 

以下鏈接包含所有&屬性

http://msdn.microsoft.com/en-us/library/2baksw0z.aspx

0

我看不出有什麼明顯的方式你的類結構可能是語法匹配到XML文檔。潛在的組織看起來完全不同。

下面的類層次結構可以從您提供的XML文檔很容易反序列化(假設你的文件涵蓋一般情況):

[Serializable] 
[XmlRoot("Booking")] 
public class Booking : List<Included> 
{ 
} 

[Serializable] 
public class Included 
{ 
    public Meals Meals { get; set; } 
    public Drinks Drinks { get; set; } 
} 

public class Meals 
{ 
    [XmlAttribute("Breakfast")] 
    public string Breakfast { get; set; } 

    [XmlAttribute("Lunch")] 
    public string Lunch { get; set; } 

    [XmlAttribute("Dinner")] 
    public string Dinner { get; set; } 
} 

public class Drinks 
{ 
    [XmlAttribute("Soft")] 
    public string Softs { get; set; } 

    [XmlAttribute("Beer")] 
    public string Beer { get; set; } 

    [XmlAttribute("Wine")] 
    public string Wine { get; set; } 
} 

然後,反序列化的代碼將是:(serializedObject是包含您的序列化的字符串對象)

XmlSerializer ser = new XmlSerializer(typeof (string)); 
XmlReader reader = XmlTextReader.Create(new StringReader(serializedObject)); 
var myBooking = ser.Deserialize(reader) as Booking; 
+0

非常感謝,我怎麼能把這個包裝成一個閱讀器? – user1641194

+0

@ user1641194抱歉沒有看到您的評論。猜猜你現在想通了。無論如何,更新我的答案。 – jbl