如何让父节点成为E4X中子节点的子节点?

时间:2015-01-28 10:26:33

标签: xml actionscript-3 e4x

如何获取父节点并使其成为子节点的子节点,同时使其成为其子节点的父节点?

例如,我有这个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>

我希望它看起来像这样:

<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 个答案:

答案 0 :(得分:0)

以下代码交换了bleep和范围父子关系:

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