1

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

[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>

我是一个新手,所以任何帮助都会很棒,不幸的是,在浏览了你已经在网上拥有的许多示例之后,我仍然无法弄清楚这一点。

4

2 回答 2

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

于 2013-10-09T07:11:42.157 回答
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;
于 2013-10-09T08:20:43.807 回答