ruk·si

⬜️ Unity
Parsing XML

Updated at 2016-10-15 15:29

C# standard libraries have good XML parser.

Markup for the data to be read:

using System.Xml.Serialization;

namespace MyXML
{
    // leaving the namespace out seems to cause it to crash :(
    [XmlRoot(ElementName="World", Namespace="http://www.example.com/...")]
    public class World
    {
        // for <World Version="10"> syntax
        [XmlAttribute("Version")]
        public string Version;

        // these are XML elements under the <World>
        public string TechnicalName;
        public Settings Settings; // Nesting works.

        // for <Cities><City/><City/></Cities> syntax
        [XmlArray("Cities")]
        [XmlArrayItem("City")]
        public List<City> Cities = new List<City>();
    }

}

Parsing:

using System.Xml;
using System.Xml.Serialization;

namespace Company.MyGame
{
    public class Parser
    {
        public static MyXML.World Parse(string xmlFilePath)
        {
            FileStream stream = null;
            MyXML.World world = null;
            try {
                var serializer = new XmlSerializer(typeof(MyXML.World));
                stream = new FileStream(xmlFilePath, FileMode.Open);
                world = serializer.Deserialize(stream) as MyXML.World;
            } finally {
                if (stream != null) { stream.Close(); }
            }
            return world;
        }
    }
}