in reply to Re: How to filter XML elements, exclude some
in thread How to filter XML elements, exclude some

Is it possible to avoid excluding name-specific elements? i.e. not to delete (and include others) but to include specific ones (and omit others)? The problem is that other elements than desc, img and size might occur
  • Comment on Re^2: How to filter XML elements, exclude some

Replies are listed 'Best First'.
Re^3: How to filter XML elements, exclude some
by poj (Abbot) on Sep 13, 2013 at 13:01 UTC
    #!perl use strict; use XML::Twig; my $twig = new XML::Twig( twig_handlers => { 'item' => \&item } ); $twig->parsefile('in.xml'); $twig->set_pretty_print('indented'); $twig->print_to_file('out.xml'); sub item { my ($t,$e) = @_; for ($e->children){ $_->delete unless ($_->name =~ /^id|name$/); } }
    poj
Re^3: How to filter XML elements, exclude some
by toolic (Bishop) on Sep 13, 2013 at 13:15 UTC
    Sure, if you spend a little more time researching:
    use warnings; use strict; use XML::Twig; my $twig = new XML::Twig( twig_handlers => { item => \&item, }, ); $twig->parsefile('in.xml'); $twig->set_pretty_print('indented'); $twig->print_to_file('out.xml'); sub item { my ( $twig, $item ) = @_; for my $c ($item->children()) { $c->cut($item) unless $c->tag() eq 'id' or $c->tag() eq 'name' ; } }
      Thank you.