Madcode
Madcode

Reputation: 81

c# XML array deserialization returns only first element

I need to deserialize next XML, but the resulting array consist only of first element:

<data>
<cards>
    <card id="1">
        <title>card1text</title>
        <category>card1cat</category>
    </card>
    <card id="2">
        <title>card2text</title>
        <category>card2cat</category>
    </card>
    <card id="3">
        <title>card3text</title>
        <category>card3cat</category>
    </card>
</cards> 
</data>

Objects to create:

[XmlRoot("data")]
public class Data
{
    [XmlArray("cards")]
    [XmlArrayItem("card", typeof(Card))]
    public Card[] cards { get; set; }
}

public class Card
{
    [XmlAttribute("id")]
    public int id { get; set; }
    public string title { get; set; }
    public string category { get; set; }
}

Deserialization:

public Data data { get; private set; }

private void Awake()
{
    var deserializer = new XmlSerializer(typeof(Data));
    var stream = new StreamReader(filePath);
    data = deserializer.Deserialize(stream) as Data;
    stream.Close();

    if (data.cards != null)
    {
        foreach (var card in data.cards)
        {
            print("card " + card.id + " " + card.title);
        }
    }
}

Deserialization seems to work fine, but I get the array of only first element from I tried using [XmlElement] instead of XmlArray, but failed as well. Thank you in advance.

Upvotes: 0

Views: 1788

Answers (1)

Z.R.T.
Z.R.T.

Reputation: 1603

for example, you can use http://xmltocsharp.azurewebsites.net/ to get C# classes from xml.

[XmlRoot(ElementName = "card")]
    public class Card
    {
        [XmlElement(ElementName = "title")]
        public string Title { get; set; }
        [XmlElement(ElementName = "category")]
        public string Category { get; set; }
        [XmlAttribute(AttributeName = "id")]
        public string Id { get; set; }
    }

    [XmlRoot(ElementName = "cards")]
    public class Cards
    {
        [XmlElement(ElementName = "card")]
        public List<Card> Card { get; set; }
    }

    [XmlRoot(ElementName = "data")]
    public class Data
    {
        [XmlElement(ElementName = "cards")]
        public Cards Cards { get; set; }
    }

Upvotes: 2

Related Questions