我需要反序列化下一个XML,但结果数组只包含第一个元素:
<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>
要创建的对象:
[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; }
}
反序列化:
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);
}
}
}
反序列化似乎工作正常,但我只获得了第一个元素的数组 我尝试使用[XmlElement]而不是XmlArray,但也失败了。 提前谢谢。
答案 0 :(得分:2)
[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; }
}