1 Reply Latest reply: May 2, 2012 7:52 PM by liangyongning RSS

    add attribute to a XML node at a specific position

    eprevot123 Community Member

      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.

        • 1. Re: add attribute to a XML node at a specific position
          liangyongning Community Member

          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);