Thursday, December 3, 2009

ActionScript3 - Update XML Data

I generally avoid XML data, it can be cumbersome to navigate, however, in my current project we use XML extensively. So I've had to deal with it.

I kind of have the parsing and filtering of XML data down...kind of. I still think a collection of objects is much simpler to handle.

My new task this week was to figure out if it was possible to update a set of XML data using ActionScript3. After googling it, I finally found the answer, yes, at least this seems to be working so far.

The XML class has replace function, or method whatever term you would like to use. It takes two arguments/parameters, the first identifies with piece of XML to replace the second is the replacement data.

So one option with the replace function is to pass in the index of the data/node you want to update as the first argument. This is the option I chose.

At first, the only way I could figure out how to calculate the index of the XML node I wanted to update was to use a for loop. However, I did more digging and discovered the childIndex() property/function of the XML class. So from there it was easy peasy.

Here is the beautiful code that brought me momentary JOY:
Sample Data:
<books>
<book id="1" title="Junk"></book>
<book id="2" title="More Junk"></book>
<book id="3" title="More More Junk"></book>
</books>

private function junk(data:Object, id:int):void{

//new data
var updatedBook:XML = data as XML;

//filter XML, and get index
var i:int = (_model.user.BooksXML..book.(@id == id).childIndex());

//-1 means no match, i assume, otherwise replace xml node at specified index
if(i > -1)
_model.user.BooksXML.replace(i, updatedBook);

}

Okay so hope that helps someone.

Now, if you need to good quick recipe, I recommend Rachael Ray's ( I LUV her) Chicken Dumping Stoup. Yum, I tried it the other nite, it was yummy and the fam liked it.

1 comment: