Easy way to add attribute to XML

Maybe I’m reinventing bicycle but..I just found 2 short ways to add attribute in XML node.

public function funnyXMLBehavior():void
{
	var xmlDemo:XML = ;

	//this is works

	xmlDemo.childNode[’@atr1′] = ‘Orange’;

	//and this is workwing too 0_o

	xmlDemo.childNode.@[’atr2′] = ‘Raspberry’;

	trace(xmlDemo.toXMLString());
}

8 Responses to “Easy way to add attribute to XML”

  1. Valery Silaev Says:

    Hmmm… If you know attribute name then even simpler approach is possible in AS3:

    xmlDemo.childNode.@attr = “Some value”

    VS

  2. Nirth Says:

    Yeah, but this is if i do know attribute. in this case it surprises me that 2 ways are equally working.

  3. Rostislav Siryk Says:

    Nice!

    I suggest

    xmlDemo.childNode.@atr[’2′] = ‘Raspberry’;

    will work too?

  4. Jloa Says:

    Hm… I dont like using the XML class, i prefer the XMLList. Try this one:

    function funnyXMLBehavior():void
    {
    var xmlDemo:XMLList = new XMLList();
    xmlDemo.childNode.@atr1 = “Orange”;
    xmlDemo.childNode.@atr2 = “Raspberry”;
    trace(xmlDemo.toXMLString());
    }
    funnyXMLBehavior();

  5. Sam Says:

    Hey if u wnt to add an attribute in an XML object u dont require ‘childNode’ also…
    just try this
    objXML.@newAttribute = ‘value’;
    it works… ;o)… amazing na…

  6. Nirth Says:

    Wow, this works man, thanks.
    Seriously why did you post that comment =)?

  7. Nirth Says:

    @Jloa
    Hehe, funny

  8. NewFlexProgrammer Says:

    Hey thanks a lot for this posting. I am new to Actionscript and this saved me lot of time. Was wondering how to add multiple attributes dynamically during runtime without knowing their names beforehand.

    All examples I saw before this were only referencing the names directly like
    xmlDemo.childNode.@atr1

    I was trying xmlDemo.childNode.@{attrName} where attrName is a string and kept hitting the wall !!