XML Gotcha – new XML(null)
Without trying it, how would you expect this to behave?
var xml:XML = new XML(null);
Personally I don’t think that constructing XML from a null object should work, but it does. I would have expected an error, like if I try to do this:
var xml:XML = new XML("<bad>hello world</tags>");
That’s about as clear a case of error throwing as you can get, I think. Why not for null?
It turns out that null is interpreted as a sort of weird XML singularity. It has one node which has no name, to which you can add attributes and children. However much you add, always the length is 1 and the toXMLString() is an empty string. Happily, this latter fact can save you from being consumed by the singularity: you can test for it by checking whether
xml.toXMLString() == "";
and take appropriate steps if it does!
I haven’t thought through all the consequences of this behaviour but it took me completely by surprise… if you can explain to me why Adobe considered this the preferred behaviour, please let me know! This is another of those hard-to-spot XML bugs like this one I found earlier. Someone, preferably Simone since he’s already on it, should wrap fixes for this stuff into a helper class!
Update
var xml:XML = new XML(null);
is – of course – the same as
var xml:XML = new XML();
The documentation doesn’t indicate that you can pass an empty value into the XML constructor, but as my colleague Simone pointed out, playerglobal.swc indicates that you can. The documentation meanwhile says that the constructor parameter for an XML object should be
Any object that can be converted to XML with the top-level XML() function.
and the top-level XML function documentation states that if you pass a null into it:
null: A runtime error occurs (TypeError exception).
However, that doesn’t throw an error either!
I started this update having seen the playerglobal.swc definition about to eat some humble pie, but this further investigation has served to strengthen my understanding of how weird this behaviour is. Be warned, this stuff is out there waiting to spoil your afternoon’s coding!
-
http://twitter.com/alecmce alecmce
