use strict; use warnings; use HTML::TreeBuilder; my $str = <King of England JAMES, by the Grace of God, King of England, Scotland, France and Ireland, Defender of the Faith... ... This first selection was written in England to establish the colony of Virginia Rights of Landowners We, greatly commending, and graciously accepting of, their Desires for the Furtherance DOC my $root = HTML::TreeBuilder->new (); $root->ignore_unknown (0); $root->parse ($str); $root->eof (); my @s1Nodes = $root->look_down ('_tag', 's1'); for my $node (@s1Nodes) { if ($node->look_up ('_tag', 'sb')) { # nested in a sb element - convert to h1 $node->{_tag} = 'h1'; } else { $node->{_tag} = 'section1'; } } print $root->as_HTML ();