Adding an XMLList back to an XML object in Flex/ActionScript 3

ActionScript 3 (and if this was in 2, please correct me) really makes working with XML easy. However, yesterday I ran into a problem that I couldn’t find the answer to. It wasn’t in the (extremely excellent) ActionScript 3.0 Cookbook nor was it in the docs. Let me back up a bit and talk about what an XMLList is. Consider XML that looks like so:

<root> <kid>Jacob</kid> <kid>Lynn</kid> <kid>Noah</kid> <foo>1</foo> <moo>2</moo> </root>

While foo and moo are typical nodes, you can consider kid to be an xmlList. To read this XML list and convert into into an array, you could do this:

for each(var favoriteNode:XML in prefsXML.favorites) { if(favoriteNode.toString() != '') favorites[favorites.length] = favoriteNode.toString(); }

Where prefsXML is an XML object, prefsXML.favorites was the repeating node, and favorites was a simple array.

So this reads in the data easily enough. What I couldn’t figure out was how to write back to the prefsXML object. I first tried this:

prefsXML.favorites = favorites;

But this generated XML that looked like so:

<favorites>1,2,3</favorites>

Turns out the solution wasn’t too complex. Ted Patrick explained it to me (although to be fair, he had to think for a second as well :) like so:

for(i=0;i < favorites.length; i++) { prefsXML.favorites[i] = favorites[i]; }

Pretty obvious once you look at it.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments