wfsp has asked for the wisdom of the Perl Monks concerning the following question:

I would like to change
<html> <head> <title>replace with</title> </head> <body> <p>text</p> <p>text</p> <p>text</p> </body> </html>
to
<html> <head> <title>replace with</title> </head> <body> <div id="links"> <div class="link"> <p>text</p> </div> <div class="link"> <p>text</p> </div> <div class="link"> <p>text</p> </div> </div> </body> </html>
My attempt.
#!/usr/bin/perl use warnings; use strict; use HTML::TreeBuilder; my $html = do{local $/;<DATA>}; my $r = HTML::TreeBuilder->new_from_content($html) or die qq{new failed\n}; for my $p ($r->look_down(_tag => q{p})){ $p->replace_with( [ q{div}, {class => q{link}}, $p ] )->delete; } my @divs = $r->look_down(_tag => q{div}); my $body = $r->look_down(_tag => q{body}); $body->replace_with( [ q{body}, [ q{div}, {id => q{links}}, @divs ] ] ); print $r->as_HTML(undef, q{ }, {p => 0}); __DATA__ <html><head><title>replace with</title></head><body> <p>text</p> <p>text</p> <p>text</p> </body></html>
Which produces what I want (as shown above).

Am I heading in the right direction?

Replies are listed 'Best First'.
Re: Using HTML::TreeBuilder to insert content into nested divs
by ikegami (Patriarch) on Nov 12, 2008 at 09:53 UTC
    If it does what you want, the only question remaining is whether your test input is representative of your actual input. I'm not sure how we can answer that.