Hacking XML2Object for Application Configurations
Posted by Ben Jackson Thu, 23 Feb 2006 19:22:00 GMT
I use Sephiroth's XML2Object for my Flash configurations. Suffice it to say that it kicks ass.
<alumni>
<name>Chuck Norris</name>
<degree>Pain</degree>
</alumni>
However, the only thing that annoys me is that instead of referring to a value the way you'd expect--alumni.degree--you have to tack on a "data" variable (alumni.degree.data) to get to that node's data. This is (I'd imagine) so you can have text in the node as well as child nodes, like:
<alumni>
<name>Chuck Norris
<degree>Pain</degree>
</name>
</alumni>
This is great for parsing HTML, but sucks for my purposes. Having to check for the (usually empty) .data var attached to each object in for...in loops is a bitch. And forgetting to tack it onto values from the config makes me appreciate this guy's state of mind . So, here's my revised version . The only thing that changed is the following lines on 64 and 65:
// old version, stores attributes and data for every node
__obj__.attributes = node.attributes;
__obj__.data = node.firstChild.nodeValue;
// new version, stores node value directly in the object
// and ignores attributes and data
var data = node.firstChild.nodeValue;
if (!isNaN(data)) { data = Number(data) }
if (node.childNodes.length <= 1 && node.firstChild.nodeType != 1) { __obj__ = data; }
Enjoy.

Thanks for doing this work Ben!
I went a couple of steps ahead with what you did and took the latest XMLObject.as from SEPY's site.
I applied your changes (thank you!!) as well as fixed some others.
Instead of using split(), i added a counter to go through the array object. Split was hacking my original array objects ;)
Line 59, instead of doing a for..in loop, I changed it to a regular for loop for index based looping of an array.
Line 131, added boolean casts to make the conversion complete from XML to Object ;)
with these changes, I now have a complete class that does conversion back and forth between XML and Objects!
You can get it here: http://mirror1.cvsdude.com/trac/osflash/xray/browser/downloads/FLASC/XMLObject.as?rev=102#L131