Forum Moderators: open

Message Too Old, No Replies

get parents of elements selected with selectNodes(xpath)

question about xpath and childNodes in javascript

         

Frumbert

2:21 am on May 13, 2005 (gmt 0)

10+ Year Member



Say I have the following xml which is loaded into the variable "xmlDoc":

<root>
<foo id="foo">
<blah id="blah">node0</blah>
<blah id="asdf">node1</blah>
<blah id="asdf">node2</blah>
</foo>
<foo id="zxcv">
<blah id="blah">node0</blah>
<blah id="asdf">node1</blah>
<blah id="asdf">node2</blah>
</foo>
</root>

Now if I do:

var xNode = xmlDoc.selectNodes("/root/foo[@id='zxcv']/blah[id='asdf']");

xNode becomes a collection of nodes (length=2) which I can iterate through like this:

for (var i=0;i<xNode.length;i++) { ... }

This is fine but each xNode is an individual entity that doesn't "know" about its position in xmlDoc. So it doesn't have any methods that are available to xmlElements - .childNodes, .hasChildNodes, .parentNode and so on.

How do I turn the result of my xPath into the index of the node in the original xmlDoc document? E.g, I want these two things to be equivalent (identical objects):

var xNode = xmlDoc.selectNodes("/root/foo[@id='zxcv']/blah[id='blah']");

var xNode = xmlDoc.documentElement.childNodes[1].childNodes[0];

so that I can do xNode.nextSibling() and so on.