无法反序列化XML

时间:2013-10-09 07:08:31

标签: c# xml deserialization

我有以下代码但无法反序列化,你能看到我出错的地方吗?它只捕获第一个数组项的第一条记录。

[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后,我仍然无法解决这个问题。

2 个答案:

答案 0 :(得分:0)

使用以下示例并在ListItem数组

中应用此语法
[XmlType("device_list")]
[Serializable]
public class DeviceList {
    [XmlAttribute]
    public string type { get; set; }

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

以下链接包含所有语法&amp;属性

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

答案 1 :(得分: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;