Skip to main content
Craig Grummitt
Inspiring
June 9, 2009
Answered

Anyone up for an XML challenge?

  • June 9, 2009
  • 1 reply
  • 519 views

I need a method to move a node up the XML hierarchy(to the same level of its parent), so if I had an XMList that looks like this:

<node label="a">
     <node label="b">
          <node label="c1">
               <node label="d1"/>
               <node label="d2"/>
          </node>
          <node label="c2"/>

     </node>
</node>

and I want to move the "d1" node up, the XMLList would end up looking like this: (with the node moved to the same level of its parent)

<node label="a">
     <node label="b">
          <node label="c1">
               <node label="d1"/>
          </node>
          <node label="d2"/>
          <node label="c2"/>
     </node>
</node>

Call the method again with the same node, and the XMLList should look like this:

<node label="a">
     <node label="b">
          <node label="c1">
               <node label="d1"/>
          </node>
          <node label="c2"/>
     </node>
     <node label="d2"/>
</node>

etc! I could probably work this out myself, but thought someone might have encountered this scenario and achieved this already...

This topic has been closed for replies.
Correct answer

It'd be something like this.

function moveNodeAfter(node1:XML, node2:XML):void
{
var idx:int = node2.childIndex();
delete node2.parent().children()[idx];
var p:XML = node1.parent();
p.insertChildAfter(node1, node2)
}


       
var xml:XML =
<node label="a">
     <node label="b">
          <node label="c1">
               <node label="d1"/>
               <node label="d2"/>
          </node>
          <node label="c2"/>
     </node>
</node>


var node:XML = xml.descendants("*").(@label=="d2")[0];
moveNodeAfter(node.parent(), node);
trace(xml);
moveNodeAfter(node.parent(), node);
trace(xml);

1 reply

Correct answer
June 9, 2009

It'd be something like this.

function moveNodeAfter(node1:XML, node2:XML):void
{
var idx:int = node2.childIndex();
delete node2.parent().children()[idx];
var p:XML = node1.parent();
p.insertChildAfter(node1, node2)
}


       
var xml:XML =
<node label="a">
     <node label="b">
          <node label="c1">
               <node label="d1"/>
               <node label="d2"/>
          </node>
          <node label="c2"/>
     </node>
</node>


var node:XML = xml.descendants("*").(@label=="d2")[0];
moveNodeAfter(node.parent(), node);
trace(xml);
moveNodeAfter(node.parent(), node);
trace(xml);

Craig Grummitt
Inspiring
June 9, 2009

That's fantastic, thanks for that Raymond.

Since my previous post, I had actually solved this myself but with many more lines of code, and I was hoping someone would be able to show me how to do this more elegantly. Much appreciated!

June 10, 2009

You're welcome Craig.