Unity scripts

XML Parser

Turn XML strings into hash/array structures. Handy for e.g. parsing an RSS feed or passing your data back and forth between Unity and your server in XML.

Download UnityScript XML Parser

Usage: parser=new XMLParser(); var node=parser.Parse("<example><value type=\"String\">Foobar</value><value type=\"Int\">3</value></example>");

Nodes are Boo.Lang.Hash values with text content in "_text" field, other attributes in "@attribute" and any child nodes listed in an array of their nodename.

any XML meta tags <? .. ?> are ignored as are comments <!-- ... -->

any CDATA is bundled into the "_text" attribute of its containing node.

e.g. the above XML is parsed to: node={ "example": [ { "_text":"", "value": [ { "_text":"Foobar", "@type":"String"}, {"_text":"3", "@type":"Int"}] } ], "_text":"" }

So to get the type of the second <value> tag you'd use: var val=node["example"][0]["value"][1]["@type"];

Notes for #pragma strict

If running in strict mode the above needs to be:

var val=((((node["example"] as Array)[0] as Hashtable)["value"] as Array)[1] as Hashtable)["@type"];

Which isn't the prettiest, so there are three helper methods.

First make sure node is cast to XMLNode:

var node:XMLNode=parser.Parse(...);

Then you can use:

var val:String=node.GetValue("example>0>value>1>@type");
var arr:XMLNodeList=node.GetNodeList("example>0>value");
var hash:XMLNode=node.GetNode("example>0>value>1");


XMLNodeList is a subclass of Array and can be treated as an Array, XMLNode is a subclass of Boo.Lang.Hash and can be treated as such.

Notes

This doesn't do any validation or XML construction, it's just an XML->Object parser. Namespaces are just handled as if the : is part of the name (so if you have a <foo:bar> element it's just listed as "foo:bar"). It's also going to create a big structure in memory if you have a big XML file, so it won't be suitable for everything.

Released under the LGPL, an extension of the GPL or if you prefer you can use this under the MIT License. If you need this code under any other license please get in touch.

Released AS IS, no warranty etc. Your mileage may vary.

Bugs, comments etc. Contact me via Twitter or Post on the Unity3D forum

Changelog

JSON Parser (alpha)

Imports JSON (JavaScript Object Notation) into a UnityScript Hashtable of hashes/arrays.

Download JSON Parser

Usage: var hash=JSON.ParseJSON(jsonString); e.g. var hash=JSON.ParseJson("{ test:\"thing\", an_array:[ \"one\",\"two\",\"three\"]}"); Debug.Log(hash["test"]);

Decidedly under-tested.

Released under the LGPL, an extension of the GPL or if you prefer you can use this under the MIT License. If you need this code under any other license please get in touch.

Released AS IS, no warranty etc. Your mileage may vary.

Bugs, comments etc. Contact me via Twitter or Post on the Unity3D forum

Changelog