title: How to get the absolute node path in XML using XPath and Ruby?
body: <p>Basically I want to extract the absolute path from a node to root and report it to the console or a file. Below is the current solution:</p>
  
  <pre><code>require "rexml/document"
  
  include REXML
  
  def get_path(xml_doc, key)
    XPath.each(xml_doc, key) do |node|
      puts "\"#{node}\""
      XPath.each(node, '(ancestor::#node)') do |el|
        #  puts  el
      end
    end
  end
  
  test_doc = Document.new &lt;&lt;EOF
    &lt;root&gt;
     &lt;level1 key="1" value="B"&gt;
       &lt;level2 key="12" value="B" /&gt;
       &lt;level2 key="13" value="B" /&gt;
     &lt;/level1&gt;
    &lt;/root&gt;
  EOF
  
  get_path test_doc, "//*/[@key='12']"
  </code></pre>
  
  <p>The issue is that it gives me <code>"&lt;level2 value='B' key='12'/&gt;"</code> as output. Desired output is <code>&lt;root&gt;&lt;level1&gt;&lt;level2 value='B' key='12'/&gt;</code> (format could be different, the main goal is to have a full path). I have only basic knowledge of <a href="http://en.wikipedia.org/wiki/XPath" rel="nofollow">XPath</a> and would appreciate any help/guidance where to look and how to achieve this.</p>