Search code examples
rubyrexml

Get immediate parent node in REXML


How do I get the immediate parent of a node with REXML? root_node() gets me the parent node of the document, but I just want the parent of the current node.


Solution

  • require "rexml/document"
    
    string = "
      <root>
        <a>
          <b>
            test
          </b>
        </a>
      </root>"
    
    doc = REXML::Document.new string
    p doc[1][1][1] #=> <b> ... </>
    p doc[1][1][1].parent #=> <a> ... </>