Friday, October 3, 2008

Flex/Actionscript XML gotcha

I spent way too long troubleshooting this issue today. I was trying to initialize an XML object with some data from my actionscript object. Here is what I was doing:
private function someFunction(myObject:Identifiable) : void {
var myXML:XML = <objectreference objectid="{}">;

Then later on in my code I was doing an XPath query like so:

var list:XMLList = myRoot.objectReference.(@objectId=='foo');

Can you spot the problem? It took me way to long to notice the problem, which was obvious once I admitted to myself that I needed to actually use the debugger.

The problem was that I had double quotes around the expression {}. The code should have been:

private function someFunction(myObject:Identifiable) : void {
var myXML:XML = <objectreference objectId={}/>;
Since having it incorrect with the quotes doesn't cause an error, I was really baffled on this.


senocular said...

(@objectId=='foo'); could also be problematic since using @ in an E4X filter can throw an error if an element of the list does not have the specified attribute.

A safer approach that avoids this error is using the attribute() method in place of @.

Theo Hultberg said...

I saw the other obvious problem: setting "objectid" but referring to "objectId", but I guess that is just a typo in the post =)

Rob McKeown said...

Good catch Theo. You're right, that was a typo.

Anonymous said...

Do you like playing in the game which you need to use runescape gold, when you do not buy runescape, you must borrowrs gold from friends, or you get runescape money. If you getcheap rs gold, you can continue this game.