in reply to Re^2: Editing HTML files
in thread Editing HTML files
The cut down example below inserts new text immediately after the opening div tag (if a text element is not found).
output#!/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>
<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>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Editing HTML files
by spivey49 (Monk) on Jul 15, 2008 at 14:10 UTC |