Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Have a look at $h->splice_content(...).

The cut down example below inserts new text immediately after the opening div tag (if a text element is not found).

#!/usr/local/bin/perl use strict; use warnings; use HTML::TreeBuilder; my $html = do{local $/;<DATA>}; my $replace = q{replaced}; my $edited = edit($html, $replace); print $edited; sub edit{ my $html = shift; my $replace = shift; # my $root = HTML::TreeBuilder->new_from_file($html_file) # or die qq{cant build tree\n}; my $root = HTML::TreeBuilder->new_from_content($html) or die qq{cant build tree\n}; my $class3 = $root->look_down( _tag => q{div}, class => q{class3}, ); die qq{class3 not found\n} unless $class3; my $rep_class3; for my $item_r ($class3->content_refs_list) { next if ref ${$item_r}; ${$item_r} = $replace; $rep_class3++; } if (not $rep_class3){ $class3->splice_content(1, 0, $replace); } #die qq{Class3 not replaced\n} unless $rep_class3; my $edited_html = $root->as_HTML(undef, qq{ }, {}); return $edited_html; } __DATA__ <div align="center" class="class1">something</div> <div align="center" class="class2">something else</div> <div align="center" class="class3"></div>
output
<html> <head> </head> <body> <div align="center" class="class1">something</div> <div align="center" class="class2">something else</div> <div align="center" class="class3">replaced</div> </body> </html>

In reply to Re^3: Editing HTML files by wfsp
in thread Editing HTML files by spivey49

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-23 13:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found