use XML::Twig; open my $ofh, '>', $output_filename or die $!; XML::Twig->new( twig_print_outside_roots => $ofh, keep_spaces => 1, twig_roots => { book => sub { my ($twig, $book) = @_; if ($book->first_child_text('title') eq 'Title of Book 1') { $book->flush($ofh); } else { $book->purge; } return 1; } }, )->parsefile($input_filename); close $ofh;