In an earlier post I post the basics of parsing xml to a class/object of type, below are the correct attributes to help the parser with coercion of values, type and values to ignore etc, which helps speed things up dramatically obviously, in this example we take some arbitrary XML as below:-
1 2 3 4 |
<Scene> <MyThing Id="915ae937" Role="Queen" StyleGUI="RoyalGUI" RewardPoints="100"/> <MyThing Id="98fac122" Role="Worker" StyleGUI="Commoner" RewardPoints="3"/> </Scene> |
And in unity for this xml would have the class set with the following xml attributes (note the use of List ‘using system.collections.generic;’ ):-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
[XmlRoot("Scene")] public class Scene { [XmlElement("MyThing")] public List<MyThing> myThings { get; set; } } public class MyThing { [XmlAttribute("Id")] public string ID { get; set; } [XmlAttribute("Role")] public string Role { get; set; } [XmlAttribute("StyleGUI")] public string StyleGUI { get; set; } [XmlAttribute("RewardPoints")] public float RewardPoints { get; set; } //internal Unity Use Only [XmlIgnore] public GameObject gameObject; [XmlIgnore] public Material material; [XmlIgnore] public float myinternalfunction() { //do something... } } |
And to take the xml text and parse it to the object:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Scene currentscene=DeserializeText<Scene>(myXMLString); public T DeserializeText<T>(string xml) { T obj=default (T); try { XmlSerializer serializer = new XmlSerializer(typeof(T)); XmlTextReader xmlReader = new XmlTextReader(new StringReader(xml)); obj = (T)serializer.Deserialize(xmlReader); xmlReader.Close(); } catch (System.Exception err) { Debug.Log ("error deserialising xml: "+err.ToString()); } return obj; } |
5182 Total Views 3 Views Today