I have a nested XML document that looks like this:
<?xml version="1.0"?>
<phone>
<name>test</name>
<descr>description</descr>
<empty/>
<lines>
<line>12345</line>
<css/>
</lines>
</phone>
I need to remove all empty XML nodes, like <empty/>
and <css/>
.
I ended up with something like:
doc = Nokogiri::XML::DocumentFragment.parse <<-EOXML
<phone>
<name>test</name>
<descr>description</descr>
<empty/>
<lines>
<line>12345</line>
<css/>
</lines>
</phone>
EOXML
phone = doc.css("phone")
phone.children.each do | child |
child.remove if child.inner_text == ''
end
The above code removes only the first empty tag, e.g. <empty/>
. I'm not able to go inside the nested block. I think I need some recursive strategy here. I carefully read the Nokogiri documentation and checked a lot of examples but I didn't find a solution yet.
How can I fix this?
I'm using Ruby 1.9.3 and Nokogiri 1.5.10.