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

I've looked through the articles and tutorials for <a href=www.XMLTWIG.com but never saw any that took several rows of data and produced a series of output rows...

Given this data:

@data = ( { age => 12, weight => 200 }, { age => 22, weight => 100 } );
How would you create this XML:
<table> <tr><td>12</td><td>200</td></tr> <tr><td>22</td><td>100</td></tr> </table>

Replies are listed 'Best First'.
Re: XML::Twig - rendering a table of data
by eff_i_g (Curate) on Jun 08, 2009 at 14:26 UTC
    I use the following approach, but be wary if you're working with wide characters. See XML::Twig, HTML::Table, and wide characters for more information.
    use warnings; use strict; use XML::Twig; use HTML::Table; my @data = ( { age => 12, weight => 200 }, { age => 22, weight => 100 } ); my @table = map { [ @{$_}{qw(age weight)} ] } @data; my $table = HTML::Table->new(\@table); my $new_elt = XML::Twig::Elt->new('table_test'); $new_elt->set_inner_xml($table->getTable()); my $twig = XML::Twig->new(pretty_print => 'indented'); $twig->set_root($new_elt); $twig->flush();
Re: XML::Twig - rendering a table of data
by Anonymous Monk on Jun 08, 2009 at 14:12 UTC
    Here's one way
    #!/usr/bin/perl -- use strict; use warnings; use XML::Twig; my @data = ( { age => 12, weight => 200 }, { age => 22, weight => 100 +} ); my $table = XML::Twig::Elt->new('table'); for my $ro (@data) { my $row = XML::Twig::Elt->new('tr'); for my $aw ( @{$ro}{ 'age', 'weight' } ) { XML::Twig::Elt->new( 'td', $aw )->paste( 'last_child', $row ); } $row->paste( 'last_child', $table ); } print " <table> <tr><td>12</td><td>200</td></tr> <tr><td>22</td><td>100</td></tr> </table> --- "; $table->print('record_c'); print "\n---\n"; $table->print('indented'); __END__ <table> <tr><td>12</td><td>200</td></tr> <tr><td>22</td><td>100</td></tr> </table> --- <table> <tr><td>12</td><td>200</td></tr> <tr><td>22</td><td>100</td></tr> </table> --- <table> <tr> <td>12</td> <td>200</td> </tr> <tr> <td>22</td> <td>100</td> </tr> </table>
      This version more "forward" :)
      #!/usr/bin/perl -- use strict; use warnings; use XML::Twig; my @data = ( { age => 12, weight => 200 }, { age => 22, weight => 100 } ); my $table = XML::Twig::Elt->new('table'); $table->insert_new_elt( 'last_child' => 'tr' => ( map { $table->new( # XML::Twig::Elt 'td', $_ ) } @{$_}{ 'age', 'weight' } ), ) for @data; $table->print('record_c'); __END__ <table> <tr><td>12</td><td>200</td></tr> <tr><td>22</td><td>100</td></tr> </table>
Re: XML::Twig - rendering a table of data
by starX (Chaplain) on Jun 08, 2009 at 14:09 UTC
    I'm not an expert on XML::Twig, and I will be sure to take note of the answer, but it seems to me that, for something like this, you might want to look into XML::Simple. Depending on how you're getting your data, you might find this tutorial useful.