- Home /
XML parsing c# in unity
Hello,
I am new to parsing xml using c# in unity, and i just want to ask what is the best way to parse an xml file in the assets folder.
i was doing some researches and found out 2 ways to do it:
-the first using serialization (using System.Xml.Serialization)
-the second using XmlNodes for each node and place data manually in an object, here is a code blow:
public team [] getTeamsFromXml(){
int i = 0;
team [] teams = new team[2];
XmlNodeList teamsNode = doc.SelectNodes ("MM_MTracker/match/teams/team");
foreach (XmlNode node in teamsNode) {
team tm = new team();
tm.id = int.Parse (node.SelectSingleNode ("id").InnerText);
tm.label = node.SelectSingleNode ("label").InnerText;
tm.flag = node.SelectSingleNode ("flag").InnerText;
tm.direction = int.Parse ( node.SelectSingleNode ("direction").InnerText );
teams[i] = tm;
i++;
}
return teams;
}
What is the best methode and is there any more options?
Thanks in advance.
Its hard for us to answer "Best Way" questions. We can help you make it work but answers based on opinion don't really fit in to UA. If it works, go with it. Also this is verging on divulgence of trade secrets :)
yes it works fine with me. But i want to consider memory consumption as well. What does "Also this is verging on divulgence of trade secrets" means?
Answer by Tiras69 · Jul 07, 2014 at 01:14 PM
Hi ! I think you should use System.Xml.serialization this allow you to create model classes. here a tutorial. in your case you will have something like that :
[XmlRoot("root")]
public class XmlFile{
[XmlArray("teams")]
[XmlArrayItem("team", typeof(Team))]
public List<Team> Teams { get; set; }
public XmlFile(){
Teams = new List<Team>();
}
}
[XmlRoot("team")]
public class Team{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("label")]
public string Label { get; set; }
[XmlAttribute("flag")]
public string Flag { get; set; }
[XmlAttribute("direction")]
public string Direction { get; set; }
}
But, It's my personnal choice. I use this method to make a big data-driven project.