1.21 gigawatts
1.21 gigawatts

Reputation: 17746

How to get all attributes on an XML node

How do I get all the attributes that exist on a XML node? For example, I have the following XML:

<item id="100">
  <defaults width="10" height="100" post="true">
</item>

I would like to get the names and values on the defaults node.

Here is some starter code:

if (item.defaults) {
    var attributes:Object = item.defaults.@*; // found in another post

    for each (var value:String in attributes) {
        trace("value "+value); // prints 10,100,true
    }
    for (var property:String in attributes) {
        trace("property "+property); // prints 0,1,2 - I need to know the names
    }
}

I found the answer:

if (item.defaults) {
    attributes = item.defaults.attributes();
    attributesLength = attributes.length();
    defaults = {};

    for each (var attribute:Object in attributes) {
        propertyName = String(attribute.name());
        defaults[propertyName] = String(attribute);
    }
}

Upvotes: 1

Views: 4858

Answers (4)

Mark Knol
Mark Knol

Reputation: 10163

This works:

var xml:XML = <item id="100"><defaults width="10" height="100" post="true"/></item>;

if (xml.defaults) 
{
    var attributes:XMLList = xml.defaults.attributes();

    for each (var prop:Object in attributes) 
    {
        trace(prop.name() + " = " + prop); 
    }
}

Upvotes: 1

Sagar Rawal
Sagar Rawal

Reputation: 1442

If you want you can convert the XML into Object

 public function xmlToObject(value:String):Object 
        {
                var xmlStr:String = value.toString();
                var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
                var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
                var resultObj:Object = decoder.decodeXML(xmlDoc);
                return resultObj;
            }

this is the function that converts xml into Object you just need to pass XML as a string and it will returns the Object.. now its easy for you to fetch data from Object.

Upvotes: 1

weltraumpirat
weltraumpirat

Reputation: 22604

Shortest one I could think of:

var defaults : Object = {};
if (item.defaults)
    for each (var att : XML in item.defaults.@*)
        defaults["" + att.name ()] = "" + att.valueOf ();

Upvotes: 3

stat
stat

Reputation: 411

This ought to get ya going:

for each (var k:XML in xml.defaults.@*)
{
    trace(k.name(), k.toXMLString());
}

Best of luck!

Upvotes: 1

Related Questions