如何在AS3中交换XML节点?

时间:2017-05-21 16:50:58

标签: xml actionscript-3

如何更改节点在其父级中的显示顺序?让我们说我想要用索引5和4交换节点。

1 个答案:

答案 0 :(得分:3)

var XX:XML =

<root>
    <node index="0" />
    <node index="1" />
    <node index="2" />
    <node index="3" />
    <node index="4" />
    <node index="5" />
    <node index="6" />
    <node index="7" />
    <node index="8" />
    <node index="9" />
</root>

var XL:XMLList = XX.children();

XX.insertChildAfter(XL[5], XL[4]);

var XXL:XMLList = XX.children();

trace(XX.toXMLString());

trace(XL[4] === XXL[4]);
trace(XL[4] === XXL[5]);
trace(XL[4] === XXL[6]);

P.S。此外,如果您想知道如何删除子节点:

delete XL[0];

trace(XX.toXMLString());

UPD :以下代码会将我们发现的错误视为任何 Flash Player版本。

var XX:XML =

<root>
    <node index="0" />
    <node index="1" />
    <node index="2" />
    <node index="3" />
    <node index="4" />
    <node index="5" />
    <node index="6" />
    <node index="7" />
    <node index="8" />
    <node index="9" />
</root>

swapNodes(XX, 4, 5);
swapNodes(XX, 0, 9);
trace(XX.toXMLString());

function swapNodes(target:XML, indexa:int, indexb:int):void
{
    // Sanity checks.
    if (!target) return;
    if (indexa < 0) return;
    if (indexb < 0) return;
    if (indexa == indexb) return;

    var anIndex:int;

    // Lets say indexa must be < indexb.
    // Just for our own convenience.
    if (indexb < indexa)
    {
        anIndex = indexa;
        indexa = indexb;
        indexb = anIndex;
    }

    var aList:XMLList = target.children();

    // Last check.
    if (indexb >= aList.length()) return;

    var aNode:XML = aList[indexa];
    var bNode:XML = aList[indexb];
    var abNode:XML = aList[indexb - 1];

    delete aList[indexb];
    target.insertChildBefore(aNode, bNode)

    if (indexb - indexa > 1)
    {
        delete aList[indexa];
        target.insertChildAfter(abNode, aNode);
    }
}