open :F html input.html ; for my $h2 in //h2 { my $h1 = $h2/following-sibling::h1[1] ; my $chunk ; if $h1 { $chunk = $h2/following-sibling::text()[following-sibling::h1[1]=$h1][preceding-sibling::h2[1]=$h2] | $h2/following-sibling::*[not(self::h2)][following-sibling::h1[1]=$h1][preceding-sibling::h2[1]=$h2] ; } else { $chunk = $h2/following-sibling::text()[preceding-sibling::h2[1]=$h2] | $h2/following-sibling::*[not(self::h2)][preceding-sibling::h2[1]=$h2] ; } if $chunk { my $div := insert element div after $h2 ; xmove $chunk into $div ; } } my $divs := wrap div //h2 ; save :F html :f output.html ;