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?


In reply to Using HTML::TreeBuilder to insert content into nested divs by wfsp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.