getXPathForElement - +comment
←Older revision Revision as of 01:55, 20 March 2008 Line 9: Line 9: For a very simple XPath usage example, see: [[Code_snippets:HTML_to_DOM#Using_a_hidden_XUL_iframe_.28complete_example.29]] For a very simple XPath usage example, see: [[Code_snippets:HTML_to_DOM#Using_a_hidden_XUL_iframe_.28complete_example.29]] -==Wrapper function==+==Node-specific evaluator function== The following function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node or Document object, while the second is a string defining an XPath expression. The following function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node or Document object, while the second is a string defining an XPath expression. Line 44: Line 44: If you are using [[XMLHttpRequest]] to read a local or remote XML file into a DOM tree (as described in [[Parsing and serializing XML]]), the first argument to <code>evaluateXPath()</code> should be <code>req.responseXML</code>. If you are using [[XMLHttpRequest]] to read a local or remote XML file into a DOM tree (as described in [[Parsing and serializing XML]]), the first argument to <code>evaluateXPath()</code> should be <code>req.responseXML</code>. -==Sample usage==+===Sample usage=== Assume we have the following XML document (see also [[How to Create a DOM tree]] and [[Parsing and serializing XML]]): Assume we have the following XML document (see also [[How to Create a DOM tree]] and [[Parsing and serializing XML]]): Line 81: Line 81: alert(results.length); alert(results.length); </pre> </pre> + +==getXPathForElement== + +The following function allows one to pass an element and an XML document to find a unique string XPath expression leading back to that element. + +<pre>function getXPathForElement(el, xml) { + var xpath = ''; + var pos, tempitem2; + + while(el !== xml.documentElement) { + pos = 0; + tempitem2 = el; + while(tempitem2) { + if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name + pos += 1; + } + tempitem2 = tempitem2.previousSibling; + } + + xpath = el.nodeName+'['+pos+']'+'/'+xpath; + el = el.parentNode; + } + xpath = '/'+xml.documentElement.nodeName+'/'+xpath; + xpath = xpath.replace(/\/$/, ''); + return xpath; +}</pre> ==Resources== ==Resources==