NOKOGIRI::XML | Delete parent where child count = 0

All I wanna do is parse the XML below and delete Peter and Sam (and
President after Sam as that will be empty after deleting Sam) as they
don’t have any children …
This nested thing is driving me crazy





On Fri, Oct 21, 2011 at 4:09 AM, Ruby M. [email protected]

25 222222222 {code}

Normally you should be able to pull this off with something like this

//[count(./)=0 and matches(text(), “\A\s*\z”)]

Apparently this does not work, but you can do this with Nokogiri

irb(main):060:0> puts d.xpath(’//[count(./)=0]’).select {|n|
/\A\s*\z/ =~ n.text}

=> nil

You can remove with

irb(main):067:0> d.xpath(’//[count(./)=0]’).select {|n| /\A\s*\z/ =~
n.text}.each &:remove
=> [#<Nokogiri::XML::Element:0x4c92fbc name=“Peter”
children=[#<Nokogiri::XML::Text:0x4c92dfa "\n ">]>,
#<Nokogiri::XML::Element:0x4c90474 name=“Sam”
children=[#<Nokogiri::XML::Text:0x4c90334 "\n ">]>]

irb(main):068:0> puts d

<?xml version="1.0"?> 23 230231111 25 222222222 => nil irb(main):069:0>

Kind regards


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs