#!/usr/bin/perl use strict; use warnings; use XML::Twig; XML::Twig->new( twig_handlers => { customBucketEnd => \&end_bucket }, pretty_print => 'indented', ) ->parse( \*DATA) ->flush; # assumes the customBucket and customDimensionName elements are ALWAYS present sub end_bucket { my( $t, $end)= @_; my @bucket_content; if( $end->prev_sibling( 'customDimensionName')->text eq 'Strategy') { while(1) { $end->cut; if( $end->tag eq 'customBucket') { last; } $end= $end->former_prev_sibling; # an obscure method that comes in handy sometimes } } else { $t->flush; } } __DATA__ Strategy Test1 SubStrategy Test2