This little script uses DBD::CSV and DBIx::XML_RDB to convert a CSV file into an XML file. Since you have know your column names ahead of time, i bypassed using Getopt::Std to query for the directory and CSV file to read from. Instead, all three items are defined at the top of the script. Your milleage may and probably will vary.

Notes:

use DBI; use File::Basename; use strict; my $dir = '.'; my $file = 'foo.csv'; my $table = (fileparse($file,'.csv'))[0]; my $cols = [qw(name id date)]; my $sep = ','; my $dbh = DBI->connect( "DBI:CSV:f_dir=$dir;csv_eol=\n;csv_sep_char=$sep;", {RaiseError=>1}, ); $dbh->{csv_tables}->{$table} = { file => $file, col_names => $cols, }; my $xml = My::DBIx::XML_RDB->new($dbh); $xml->DoSql("select * from $table"); print $xml->GetData(); package My::DBIx::XML_RDB; use base qw(DBIx::XML_RDB); sub Initialise { my ($self,$dbh) = @_; $self->{dbh} = $dbh; $self->{output} = qq|<?xml version="1.0"?>\n<DBI>\n|; return 1; }
And here is a sample CSV file you can use with the supplied file, directory, and column names. Save this as foo.csv in the same directory as the script:
string,10,07/13/1970
foo,999999,04/01/1940
bar,0,12/31/1999

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
CSV to XML (the quick and not so dirty way)
by jeffa (Bishop) on Jun 28, 2002 at 22:56 UTC
    Since DBIx::XML_RDB has been replaced by the new and improved XML::Generator::DBI - here is a much better way to convert CSV to XML:
    use strict; use DBI; use File::Basename; use XML::Generator::DBI; use XML::Handler::YAWriter; my $dir = '.'; my $file = 'foo.csv'; my $table = (fileparse($file,'.csv'))[0]; my $cols = [qw(name id date)]; my $sep = ','; my $dbh = DBI->connect( "DBI:CSV:f_dir=$dir;csv_eol=\n;csv_sep_char=$sep;", {RaiseError=>1}, ); $dbh->{csv_tables}->{$table} = { file => $file, col_names => $cols, }; my $ya = XML::Handler::YAWriter->new(AsFile => "-"); my $generator = XML::Generator::DBI->new( Handler => $ya, dbh => $dbh, Indent => 1, ); $generator->execute("select * from $table");
    Much better, but i still enjoy a little OO hacking now and then. :D

    UPDATE:
    Silly /me - XML::CSV:

    perl -MXML::CSV -e '$o=XML::CSV->new;$o->parse_doc(shift,{headings=>sh +ift});$o->print_xml' no_headings.csv perl -MXML::CSV -e '$o=XML::CSV->new;$o->parse_doc(shift,{headings=>sh +ift});$o->print_xml' headings.csv 1

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)