views:

115

answers:

2

How do I get the root node of an XML object in Actionscript?

One would think that I could say this:

var Node:XMLNode = XMLVar as XMLNode;

But although XMLVar is of type XML, Node will = null.

So how do I do it?

+1  A: 

You code is a little confusing because you are using uppercase first characters for you variable names. Take a look at Adobe's coding conventions for AS3.

var xmlData:XML = new XML();
var node:XMLNode = xmlData.firstChild();

This example is pretty useless, but it just demonstrate the method.

Use the XML object's firstChild method. To get the first node as a XMLNode object.

TandemAdam
+1  A: 
var node:XMLNode = xmlVar as XMLNode;

although xmlVar is of type XML

XML and XMLNode are not compatible in ActionScript-3. XML class of AS2 (and its related classes) has been renamed to flash.xml.XMLDocument in AS3.

The XMLNode/XMLDocument class represents the legacy XML object that was present in ActionScript 2.0 and that was renamed in ActionScript 3.0. In ActionScript 3.0, consider using the new top-level XML class and related classes instead, which support E4X (ECMAScript for XML). The XMLNode/XMLDocument class is present for backward compatibility.

An object of type XML cannot be cast directly to XMLNode. Since you're trying to cast with as keyword, it just returns null instead of raising an alarm saying the cast failed.


And as already mentioned, consider using lowerCase names for variables, as UpperCase names are normally used for naming classes.

Amarghosh
Little mixup in above response, XML is AS3 while XMLDocument is AS2. Otherwise this answer is absolutely correct. (For the benefit of the original poster)
Tyler Egeto
@Tyler AS2 had a top level `XML` class; it has been retained as `flash.xml.XMLDocument` in AS3 for backward compatibility. The top level `XMLNode` class in AS2 has been moved to `flash.xml.XMLNode`. AS3 has a top level `XML` class that supports e4x. Search for "XML class" in this AS2 to AS3 migration reference http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/migration.html
Amarghosh