Rockyboy_ruby
Rockyboy_ruby

Reputation: 233

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

All I want to do is parse the XML below and delete Peter and Sam element as they dont have any children (also can say empty) and President element after that as it will be empty. This nested thing is driving me crazy!

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

Upvotes: 1

Views: 311

Answers (1)

pguardiario
pguardiario

Reputation: 54984

It looks like you want:

doc.xpath('//*[not(*) and normalize-space(text())=""]').remove
  • not(*) selects nodes without children
  • normalize-space(text())="" selects nodes with empty text (trimmed whitespace)

Do it 2x to remove President too.

Upvotes: 4

Related Questions