2013-10-09 140 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