0

How do I take a parent node and make it a child of it's own child node while at the same time making it the parent of it's grand children?

For example, I have this XML:

<root>
  <range>
    <a>
    <b>
    <c>
  </range>
  <range>
    <a>
    <b>
    <c>
  <range>
  <bleep>
      <range>
        <a>
        <b>
        <c>
      </range>
      <range>
        <a>
        <b>
        <c>
      </range>
  </bleep>
</root>

I want it to look like this:

<root>
  <range>
    <a>
    <b>
    <c>
  </range>
  <range>
    <a>
    <b>
    <c>
  <range>
  <range>
     <bleep>
        <a>
        <b>
        <c>
     </bleep>
  </range>
  <range>
     <bleep>
        <a>
        <b>
        <c>
     </bleep>
  </range>
</root>
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • I think you should construct a new XML with all your node's direct children to be placed instead of the node, and then add a node to each of them with the same name as the replaced node, then add all other children into the added node. Or, if E4X allows that, extract the node to replace out of the original XML and do the same with the existing XML. – Vesper Jan 28 '15 at 19:49
  • I receive the XML as the first example so I can't change that. It's the format exported by a very popular program so it's unlikely to change in the future. – 1.21 gigawatts Jan 28 '15 at 21:15

1 Answers1

0

The following code swaps the bleep and range parent child relationship:

var xml:XML = myXML.copy();
trace(xml);

const CharacterStyleRange:String = "range";
const HyperlinkTextSource:String = "bleep";

var children:XMLList = xml.children();
var newChildren:XMLListCollection = new XMLListCollection();

// loop through paragraph children
for each (var child:XML in children) {
    // if CharacterStyleRange
    if (child.name() == CharacterStyleRange) {
        newChildren.addItem(child);
    }

    // if HyperlinkTextSource
    // get ranges and insert hyperlink text source
    else if (child.name() == HyperlinkTextSource) {
        var ranges:XMLList = child.CharacterStyleRange;

        for each (var range:XML in ranges) {
            var rangeChildren:XMLList = range.children();
            var newChild:XML = child.copy();
            newChild.setChildren(rangeChildren);
            range.setChildren(newChild);
            newChildren.addItem(range);
        }
    }
}

var newChildrenXML:XMLList = newChildren.copy();
xml.setChildren(newChildrenXML);
trace(xml);
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231