wfsp has asked for the wisdom of the Perl Monks concerning the following question:
to<html> <head> <title>replace with</title> </head> <body> <p>text</p> <p>text</p> <p>text</p> </body> </html>
My attempt.<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>
Which produces what I want (as shown above).#!/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>
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 |