<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: xpath code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Thu, 21 Aug 2008 01:49:25 GMT</pubDate>
    <description>DZone Snippets: xpath code</description>
    <item>
      <title>Get XPath</title>
      <link>http://snippets.dzone.com/posts/show/4349</link>
      <description>Given a node this will return an array containing the XPath&lt;br /&gt;Usage:&lt;br /&gt;&lt;br /&gt;getXPath(document.getElementById('myelement'));&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;      function getXPath(node, path) {&lt;br /&gt;        path = path || [];&lt;br /&gt;        if(node.parentNode) {&lt;br /&gt;          path = getXPath(node.parentNode, path);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        if(node.previousSibling) {&lt;br /&gt;          var count = 1;&lt;br /&gt;          var sibling = node.previousSibling&lt;br /&gt;          do {&lt;br /&gt;            if(sibling.nodeType == 1 &amp;&amp; sibling.nodeName == node.nodeName) {count++;}&lt;br /&gt;            sibling = sibling.previousSibling;&lt;br /&gt;          } while(sibling);&lt;br /&gt;          if(count == 1) {count = null;}&lt;br /&gt;        } else if(node.nextSibling) {&lt;br /&gt;          var sibling = node.nextSibling;&lt;br /&gt;          do {&lt;br /&gt;            if(sibling.nodeType == 1 &amp;&amp; sibling.nodeName == node.nodeName) {&lt;br /&gt;              var count = 1;&lt;br /&gt;              sibling = null;&lt;br /&gt;            } else {&lt;br /&gt;              var count = null;&lt;br /&gt;              sibling = sibling.previousSibling;&lt;br /&gt;            }&lt;br /&gt;          } while(sibling);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        if(node.nodeType == 1) {&lt;br /&gt;          path.push(node.nodeName.toLowerCase() + (node.id ? "[@id='"+node.id+"']" : count &gt; 0 ? "["+count+"]" : ''));&lt;br /&gt;        }&lt;br /&gt;        return path;&lt;br /&gt;      };&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 23 Jul 2007 20:57:04 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4349</guid>
      <author>sprsquish (Jeff Smick)</author>
    </item>
  </channel>
</rss>
