Saturday, May 12, 2007

toplevel.XML.Traversing XML structures

I have found Adobe's documentation on "Traversing XML Structures" to cause a little confusion. Nothing Adobe says is wrong. There aren't any features that they've hidden from you. But if you only read parts of the documentation you can get confused fairly easily.

Confusion can be boiled down to one concept in the "Accessing parent and child nodes" substopic. To paraphrase, if you have the variable:

var myXML:XML = <order><book><title>Dictionary</title></book></order>;

since there is only one book tag and that book tag has only one child, you don't have to use indexes when traversing the XML. In other words, you can use either of the following:

myXML.book[0].title[0];
myXML.book.title;


Well it depends on how you are using the variables. The top statement returns an object of XML type. The bottom statement returns an object of XMLList type. This can be important depending on what you are using the result for. For example, let's say you are trying to determine if myXML.book[0] has any title children, you have a few options. Two of them are:

var test1:Boolean = (myXML.book[0].title[0] != null);
var test1:Boolean = (myXML.book[0].title.length() != 0);


Notice that if myXML.book[0] has no children and you try to check that is has children using (myXML.book[0].title != null), the check will always evaluate to true because the left side of the statement will always evaluate to an XMLList even if the XMLList has a length of 0.

This is more important because almost all XML and XMLList functions (such as the attribute (@), decendent (..), etc) work this way and return XMLLists. The only common function that returns an XML object is getting an XML node by index. So if you're having trouble using these function, make sure this confusion isn't what is tripping you up.
"Flex", "ActionScript" and possibly "MXML" are probably trademarks of Adobe Systems Incorporated.
"Adobe" is a trademark of Adobe Systems Incorporated.
This site is in no way endorsed or sponsored by Adobe Systems Incorporated.
Content Copyright © 2007 Daniel Freiman.
Site Design Copyright by its copyright holder.
The Flex Non-Docs reserves the right to remove comments for any reason.
All ActionScript and MXML code (and ONLY ActionScript and MXML code) on this website is available under the MIT License.