tags:

views:

54

answers:

1

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?

+1  A: 

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.

audiodude
Awesome! Will give it a go when I get home tonight.
Mongus Pong
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