Search code examples
xmlrubyrexml

Deleting all child nodes and text of an element


With reXml using Ruby, I have a particular element and I want to completely clear out all its child nodes and text.

I just cannot work out how to do this.

Given this :

<ug>
  <oog>
    Delete<delete/>all<delete/>this
  </oog>
</ug>

I want to delete all the children of oog, to end up with this :

<ug>
  <oog>
  </oog>
</ug>

I can get it to delete the nodes using :

  blah = REXML::Document.new('<ug><oog>Delete<delete/>all<delete/>this</oog></ug>')
  oog = blah.elements['//oog']
  oog.elements.delete_all '*'

  puts blah.to_s

But this doesnt delete the text, so I still have

<ug>
  <oog>
    Deleteallthis
  </oog>
</ug>

Any ideas?


Solution

  • Try doing what you're already doing, then adding :

    while node = oog.get_text
      oog.delete node
    end
    

    REXML treats text nodes differently from regular Elements for various reasons that I can't remember.