I plan to blog useful code snippets regularly. Just little bits of ActionScript that help me in my day to day coding.

To start, I want to share a little snippet that is possible the most useful 14 lines of code I ever wrote. It's a simple addition to the XMLNode prototype that lets you index and reference a node's childnodes based on any attribute or the nodeName. It will be less useful with AS2.0, due to the xPath implementation, but I expect it will still be faster, and will do the job in many situations.

I'm not sure I would ever have had the patience to write gModeler if it were not for this little gem.

Read on for the code...

Here is the code, and comments. Hopefully it comes through ok - I'm new to this game. :)


/*
Code snippet by Grant Skinner [ http://www.gskinner.com ]
This is one of those ultra simple snippets that I can't live without. All it does is take an xml node, and creates an index object for it.
The index object references the child nodes by the value of the attribute passed to the method, or by nodeName.

Usage:
myXMLNode.indexOn(attributeName);
myVariable = myXMLNode.index.attributeValue;

// where attributeName is the name of the attribute to base the index on
// or "nodeName" to index by the node names.
*/
XMLNode.prototype.indexOn = function(fAttribute) {
  this.index = {};
  var children = this.childNodes;
  if (fAttribute == "NODENAME") {
    for (var i in children) {
      this.index[children[i].nodeName] = children[i];
    }
  } else {
    for (var i in children) {
      this.index[children[i].attributes[fAttribute]] = children[i];
    }
  }
  delete(this.index[null]);
}


Add this code near the beginning of a flash movie, and you can use the indexOn method on any xml node to create an index for the node based on the attribute name you passed (or the nodeName if you pass in "NODENAME"). Here is a simple example:

// create the xml object:
myXML = new XML("<book><chapter name='test1'/><chapter name='test2'/><chapter name='test3'/></book>");
// get the root node (book):
myBook_xml = myXML.firstChild;
// create an index based on the "name" attribute
myBook_xml.indexOn("name");
// access the childNode with the name attribute equal to "test2", and trace it's value:
myChapterNode = myBook_xml.index["test2"];
trace("test2 xml= " + myChapterNode);