in reply to prune xml of empty elements

XML::Twig can prune out all elements which have no text content:
use warnings; use strict; use XML::Twig; my $str = <<EOF; <note> <to> <person>Satan</person> </to> <from via="postcard" russia="with love">moneypenny</from> <heading></heading> <body></body> </note> EOF my $t = XML::Twig->new( pretty_print => 'indented', twig_handlers => { _all_ => sub { $_->delete() unless $_->text() } + } ); $t->parse($str); $t->print(); __END__ <note> <to> <person>Satan</person> </to> <from russia="with love" via="postcard">moneypenny</from> </note>

Replies are listed 'Best First'.
Re^2: prune xml of empty elements
by Anonymous Monk on Jul 15, 2011 at 08:52 UTC
    Updated based on this clarification
    #!/usr/bin/perl -- use warnings; use strict; use XML::Twig; my $str = <<'EOF'; <note> <to> <person>Satan</person> </to> <from via="postcard" russia="with love">moneypenny</from> <heading></heading> <body></body> <fudge a="body"></fudge> <fudge><a></a></fudge> <fudge><a body="good"></a></fudge> </note> EOF my $t = XML::Twig->new( pretty_print => 'indented', twig_handlers => { _all_ => sub { $_->delete() unless $_->has_child or $_->has_atts }, }, ); $t->parse($str); $t->print(); __END__ <note> <to> <person>Satan</person> </to> <from russia="with love" via="postcard">moneypenny</from> <fudge a="body"></fudge> <fudge> <a body="good"></a> </fudge> </note>