DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

From Database Records To XML

  • submit to reddit
        Here is a quick way to convert database records to XML using XML::Simple.


use warnings;
use strict;
use XML::Simple;
use DBI;

my $dbh = DBI->connect('DBI:mysql:MYDATABASE','user','password')
  or die DBI->errstr;

# Get an array of hashes
my $recs = $dbh->selectall_arrayref('SELECT * FROM contents',{ Columns => {} });

# Convert to XML where each hash element becomes an XML element
my $xml = XMLout( {record => $recs}, NoAttr => 1 );

print $xml;


For a table with fields named "id", "entry", and "modified", the output would be:

    <entry>1932 - 1939</entry>
    <modified>2005-04-15 22:24:44</modified>
    <entry>Yet another entry</entry>
    <modified>2005-04-15 22:25:00</modified>
    <entry>More stuff here</entry>
    <modified>2005-04-15 22:25:13</modified>