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:
- BYOEC (bring your own error-checking - hey,
how about Ovid's CSV Database Validation?).
- DBIx::XML_RDB is subclassed in order to make it share
the DBI::db handle created via DBD::CSV. DBIx::XML_RDB will
also complain about some warnings - just ignore them. :D
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)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.