Descendant accessors and namespaces in AS3.0

Posted: 08/01/08

An image of Descendant accessors and namespaces in AS3.0

I recently encountered a problem, and with it, the lack of documentation around the use of the descendant accessor (double dot ..) in ActionScript 3.0. I was writing a web service adapter that would obviously need to traverse various XML namespaces (such as soap: and wsdl:), but found the shorthand notation wasn't working as expected.

Problem:

You're trying to use the double dot (..) descendant accessor with an XML document that declares one for more namespaces. When you try to use var myTags:XMLList = myXML..ElementName nothing appears to happen.

Even if you have XML like this:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">

<s:Body>

<ServiceResponse>

<Result xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

<Item>

<Id>1</Id>

<Text>Hello</Text>

</Item>

<Item>

<Id>2</Id>

<Text>World</Text>

</Item>

</Result>

</ServiceResponse>

</s:Body>

</s:Envelope>

</strong>

And declare a default XML namespace:

<strong>var ns:Namespace = myXML.namespace( "s" );

default xml namespace = ns;

Still myTags has a value of null

Answer:

var myTags:XMLList = myXML..*::Tag

In addition to using the (..) descendant accessor, because you're now working with XML namespaces, you need to indicate that the tag you're trying to access (at any depth) can belong to any (*) namespace. Normally to declare a namespace when traversing XML, you'd use myXML..ns::Tag, but by using the wildcard * it will pick-up the specified tags belonging to any namespace in the document.

The clear limitation here is that if you only want to pick-up tags from a particular namespace inside your XML, such as wsdl or soap, you would need to specify these as a qualified Namespace object in the place of the wildcard.

More about the descendent accessor

Keywords for this post: flash, actionscript 3, flex, web service, descendent accessor, xml, soap