2

lookin my XML example, how I do to Deserialize it? But I need to Deserialize the Xml Element array. How I do it?

<hotels num="1">
<hotel num="1" item="2"></hotel>
<hotel num="2" item="2"></hotel>
<hotel num="3" item="2"></hotel>
<hotel num="4" item="2"></hotel>
<hotel num="5" item="2"></hotel>
</hotels>

[Serializable]
[XmlRoot("hotels")]
public class Hotels
{
[XmlElement("id")]
public string id {  get; set; }
[XmlElement("hotel")]
public Hotel hotel { get; set; }
}

[Serializable]
[XmlRoot("hotel")]
public class Hotel
{
[XmlElement("id")]
public string id {  get; set; }
[XmlElement("item")]
public string item {  get; set; }
}
2
  • whats the DataAnotation is using to determine that element is xml array? Commented Aug 24, 2012 at 21:23
  • 2
    I don't think this will solve your problem, but the Hotel property on the Hotels class should probably be changed to a List<Hotel> or Hotel[] Commented Aug 24, 2012 at 21:31

1 Answer 1

7

Try like this:

[XmlRoot("hotels")]
public class HotelData
{
    [XmlAttribute("num")]
    public string Id { get; set; }

    [XmlElement("hotel")]
    public List<Hotel> Hotels { get; set; }
}

public class Hotel
{
    [XmlAttribute("num")]
    public string Id { get; set; }

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

and then deserialize:

public class Program
{
    static void Main()
    {
        var serializer = new XmlSerializer(typeof(HotelData));
        using (var reader = XmlReader.Create("test.xml"))
        {
            var data = (HotelData)serializer.Deserialize(reader);
            Console.WriteLine(data.Id);
            foreach (var hotel in data.Hotels)
            {
                Console.WriteLine("num: {0}, item:{1}", hotel.Id, hotel.Item);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

but I don't need to set XmlArray in [XmlElement("hotel")] public List<Hotel> Hotels { get; set; } ?
Why won't you need? Your XML seems to contain an array of hotels. At least the example you have shown here. But maybe your actual XML is different, is it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.