Skip navigation
Currently Being Moderated

add attribute to a XML node at a specific position

May 2, 2012 5:42 AM

Tags: #as3 #xml #attribute

I have this XML :

var myNode:XML = <node attribute="123"/>

I know how to add an attribute to the node :

myNode.@otherAttribute = "abc";

But this adds the attribute to the end. What if I want to add it as the first attribute ? I would like to have :

<node otherAttribute="abc" attribute="123"/>

I know it is possible to add a child node to a specific position with insertChildAfter() or insertChildBefore() but I don't know if it's possible for an attribute.

 
Replies
  • Currently Being Moderated
    May 2, 2012 7:52 PM   in reply to eprevot123

    there's no native method for this, maybe you should create some functions for this. just like

     

    private function setAttribute(node:XML, name:String, value:String, index:int = -1):void

    {

        var attrs:XMLList = node.attributes().copy(),

            l:int = attrs.length();

        if(index == -1 || index > l - 1)

        {

            node.@[name] = value;

        }

        else

        {

            delete node.@*;

            var idx:int = 0;

            for (var i:int = 0; i < l + 1; i++)

            {

                if(i == index)

                {

                    node.@[name] = value;

                }

                else

                {

                    var attr:XML = attrs[idx];

                    node.@[attr.name()] = attr.toString();

                    idx++;

                }

            }

           

        }

    }

     

    and use it like this:

    setAttribute(myNode, "otherAttribute", "abc", 0);

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points