PDA

View Full Version : Swap 2 Elements


safalkishore
09-29-2003, 08:17 PM
> I have an XML strcture as follows :
>
> <Tree>
> <Folder count="1" Name="Design Build">
> <Folder count="2" Name="Main First">
> <Folder count="3" Name="Sub1"/>
> </Folder>
> <Folder count="4" Name="Main Second">
> <Folder count="5" Name="Sub2"/>
> </Folder>
> </Folder>
> </Tree>
>
> The output required is as follows
>
> <Tree>
> <Folder count="1" Name="Design Build">
> <Folder count="4" Name="Main Second">
> <Folder count="5" Name="Sub2"/>
> </Folder>
> <Folder count="2" Name="Main First">
> <Folder count="3" Name="Sub1"/>
> </Folder>
> </Folder>
> </Tree>


> ie if you notice here Folder "Main FIrst" and "Main Second" have been
> swapped along with their childnodes
> I am looking at a piece of code that can do this.I only wish to swap 2
> nodes at a time.

I am making use of the DOM and not XSLT
I would like to know how i can swap nodes after loading the XML document shown

Please let me know how i could do this using XML DOM (Javascript).

liorean
09-29-2003, 08:29 PM
Hmm, seems like you'll be wanting to do like this:

1. Clone element A using clonedA=elementA.cloneNode(true);
2. Use elementB.parentNode.insertBefore(clonedA, elementB) on element B.
3. Use elementA.parentNode.replaceNode(elementB, elementA); on element A.

Microsoft has a proprietary switchNodes as well, but I prefer to use the W3C DOM if I can.

Alex Vincent
09-30-2003, 02:05 AM
Actually, you don't need to do a clone like you would with normal JS. You just need to know where you're inserting.

var nextNode = elementB.nextNode;
elementA.parentNode.insertBefore(elementB, elementA)
nextNode.parentNode.insertBefore(elementA, nextNode);

liorean
09-30-2003, 06:50 AM
Yeahm you're right about that. But then we need to take the cases where there exists no nextNode in consideration as well.

LeXRus
10-02-2003, 04:13 PM
i think replaceChild() is faster

<xml id="xmlsrc">
<Tree>
<Folder count="1" Name="Design Build">
<Folder count="2" Name="Main First">
<Folder count="3" Name="Sub1"/>
</Folder>
<Folder count="4" Name="Main Second">
<Folder count="5" Name="Sub2"/>
</Folder>
</Folder>
</Tree>
</xml>

<script>
var x=new ActiveXObject('Msxml.DOMDocument');
with(x)with(document){
x.async=true;
loadXML(xmlsrc.xml);
write('<xmp>'+xml+'</xmp>');
write('<hr>');
var node0=selectSingleNode('//*[@count=3]');
var node1=selectSingleNode('//*[@count=5]');
node0.parentNode.replaceChild(node1.cloneNode(true),node0);
node1.parentNode.replaceChild(node0.cloneNode(true),node1);
write('<xmp>'+xml+'</xmp>');
}
</script>

liorean
10-02-2003, 04:18 PM
Except for the proprietary code, that seems to do it, yes. However, do you need to clone both of the nodes? I only used cloneNode because I'd lose the position reference of the first node if I moved the actual node instead of a clone of it.