2
我目前在unity3D中製作遊戲。我有一個xml文檔,其中包含許多用各種紙牌填充的套牌。該XML文件看起來是這樣的:在c#中反序列化嵌套的xml(Unity-script)
<?xml version="1.0" encoding="utf-8" ?>
<CardCollection>
<Cards>
<Deck DeckId="1">
<Card Id="1">
<CardElement1></CardElement1>
<CardElement2></CardElement2>
</Card>
<Card Id="2">
<CardElement1></CardElement1>
<CardElement2></CardElement2>
</Card>
<Card Id="3">
<CardElement1></CardElement1>
<CardElement2></CardElement2>
</Card>
</Deck>
<Deck DeckId="2">
<Card Id="1">
<CardElement1></CardElement1>
<CardElement2></CardElement2>
</Card>
</Deck>
</Cards>
</CardCollection>
我有一個類Card.cs看起來像下面這樣:
using System.Xml.Serialization;
public class Card {
[XmlAttribute("Id")]
public int id;
[XmlElement("CardElement1")]
public string cardElement1;
[XmlElement("CardElement2")]
public string cardElement2;
}
和A類Deck.cs:
使用系統。 Xml.Serialization;
public class Deck {
[XmlAttribute("DeckId")]
public int deckId;
[XmlArray("Card")]
public Card[] cards;
}
我使用了一個名爲CardContainer類來填充這個信息的列表甲板:
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using UnityEngine;
[XmlRoot("CardCollection")]
public class CardContainer {
[XmlArray("Cards")]
[XmlArrayItem("Deck")]
public List<Deck> decks = new List<Deck>();
public static CardContainer Load(string path)
{
TextAsset xml = Resources.Load<TextAsset>(path);
XmlSerializer serializer = new XmlSerializer(typeof(CardContainer));
StringReader reader = new StringReader(xml.text);
CardContainer cards = serializer.Deserialize(reader) as CardContainer;
reader.Close();
return cards;
}
}
我可以用這個代碼片段甲板的ID用的保持:
CardContainer cardContainer = CardContainer.Load(path);
foreach(Deck deck in cardContainer.decks){
Debug.Log(deck.deckId);
}
但是,我不知道如何反序列化和填充Deck對象中的Card-array。