http://www.perlmonks.org?node_id=273504

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

Hello,

What I am trying to do is take a string of valid HTML, convert it into a Perl Data structure so I can easily modify the individual parts, then output the modified structure back as HTML again.

At first I though that this would be fairly easy using XML::Simple, I seem to be running into a problem when converting back to HTML though. Seems that some tags are improperly being interpreted as tag attributes, rather than the nested tags that they started out as.

I have read through the XML::Simple Documentation but have not been able to gleam a way of getting what I want out of it.

I may be going about this the wrong way entirely. Maybe this cannot effectively be done? I would be very interested in any suggestions on how I might go about doing this. I am not set on using XML::Simple, it just seemed the closest fit to the solution I could find.

Here is a code snippet that I have been working with, that almost gives me what I want.

#!/usr/local/bin/perl5.6.0 -w use strict; use Data::Dumper; use XML::Simple; my $html = q{ <html> <head> <title> test </title> </head> <body bgcolor='red' > <errors> <TMPL_IF NAME='INVALID_WIDGET_SIZE' > waka waka </TMPL_IF> <TMPL_IF NAME='INVALID_WIDGET_COLOR' > waka waka waka </TM +PL_IF> </errors> <table> <tr colspan='2'> <td> text </td> <td> text2 </td> </tr> </table> </body> </html> }; my $xs = XML::Simple->new(); my $ref = $xs->XMLin( $html, ForceContent => 1, KeepRoot => 1, Content +Key => 'content' ); for ( @{$ref->{html}->{body}->{errors}->{TMPL_IF}} ) { if ( $_->{NAME} eq 'INVALID_WIDGET_COLOR' ) { $_->{content} = 'changed it'; } } my $html_data = $xs->XMLout( $ref ); print Dumper( $html_data ); __END__

Outputs:

:!./html-test.pl $VAR1 = '<opt> <html name="head"> <title> test </title> </html> <html bgcolor="red" name="body"> <errors> <TMPL_IF NAME="INVALID_WIDGET_SIZE"> waka waka </TMPL_IF> <TMPL_IF NAME="INVALID_WIDGET_COLOR">changed it</TMPL_IF> </errors> <table colspan="2" name="tr"> <td> text </td> <td> text2 </td> </table> </html> </opt> ';

As you can see, it seems to misinterpret the 'head' and 'tr' tags as attributes to the enclosing tags. it also does not seem to properly nest everything correctly.

Any suggestions or ideas on how I can correct this, or do it another way would be much appreciated.

Best Regards,
Wonko