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

All I wanna do is parse the XML below and delete Peter and Sam as they
don't have any children

{code}
<Office id="xyz" scope="node">
  <John>
    <age>23</age>
    <ssn>230231111</ssn>
  </John>
  <Peter>
  </Peter>
  <John>
    <age>25</age>
    <ssn>222222222</ssn>
  </John>
  <Sam>
  </Sam>
</Office>
{code}

···

--
Posted via http://www.ruby-forum.com/.

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

//*[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}
<Peter>
</Peter>
<Sam>
</Sam>
=> 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"?>
<Office id="xyz" scope="node">
<John>
   <age>23</age>
   <ssn>230231111</ssn>
</John>

<John>
   <age>25</age>
   <ssn>222222222</ssn>
</John>

</Office>
=> nil
irb(main):069:0>

Kind regards

robert

···

On Fri, Oct 21, 2011 at 4:09 AM, Ruby Mania <prateek123@gmail.com> wrote:

All I wanna do is parse the XML below and delete Peter and Sam as they
don't have any children

{code}
<Office id="xyz" scope="node">
<John>
<age>23</age>
<ssn>230231111</ssn>
</John>
<Peter>
</Peter>
<John>
<age>25</age>
<ssn>222222222</ssn>
</John>
<Sam>
</Sam>
</Office>
{code}

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/