[英]c# XML array deserialization returns only first element
I need to deserialize next XML, but the resulting array consist only of first element: 我需要反序列化下一个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>
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. 反序列化似乎工作正常,但是我尝试使用[XmlElement]而不是XmlArray时得到了只有第一个元素的数组,但同样失败了。 Thank you in advance.
先感谢您。
for example, you can use http://xmltocsharp.azurewebsites.net/ to get C# classes from xml. 例如,您可以使用http://xmltocsharp.azurewebsites.net/从xml获取C#类。
[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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.