0

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?

Mongus Pong
  • 11,337
  • 9
  • 44
  • 72

1 Answers1

3

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.

Mongus Pong
  • 11,337
  • 9
  • 44
  • 72
audiodude
  • 1,865
  • 16
  • 22
  • Awesome! Will give it a go when I get home tonight. – Mongus Pong Mar 03 '10 at 10:25
  • Yup that does it nicely! Thanks. btw.. I had to edit your answer because for some reason it didnt let me upvote unless the answer was edited.. not sure why, but anyway I just put a space after the : ! You deserve many upvotes here in my eyes!!! – Mongus Pong Mar 03 '10 at 21:47