A place where things actually work,
with a sense of humor.
Comments

admin
0 comments


keywords:

Back to Perl: simplecsv2xml
i used to use Perl a lot, but I got rusty. Today I needed to convert a bunch of typical CSV files into "XML" Quick and Dirty, simple flat files.
It's a sad world when a professional $150+/hr developer only knows how to read XML. My guess is they code in Java or Dot.Not. Heck, Maybe MS-Visual Basic.

Mine is not to wonder why... mine is just to do or die. I went looking for what I wanted.. most of the solutions were just too complex, so I started from scratch and ened up with a simple Perl script to convert CSV to XML.. Why perl? Fast and easy parser of STDIN/STDOUT. This is NOT what is used in the final project, but it is something that works and many people (and sometimes me) just need a quick CSV to XML conversion.

Usage:   simplecsv2xml.pl <infile >outfile
 


#!/usr/bin/perl
# Mikes Uber Simple CSV to XML Parser
use Text::CSV;
$csv = Text::CSV->new();
$i = 0 ;
print "<?xml version="1.0" encoding="UTF-8"?> " ;
print "<document> " ;
while(<STDIN>) {
$status = $csv->parse($_); # parse a CSV string into fields
if($i < 1) {
@key = $csv->fields() ; # get the parsed fields
# assumes the first line is the key/field names
} else {
@data = $csv->fields(); # get the parsed fields
} ;
#now make it XML-ish.
if($i > 0) {
$r = 0 ;
print '<row>' ;
foreach(@data) {
if($key[$r] ne '') {
print '<'. $key[$r] . '>' . $_ . '</' . $key[$r] . '>' ;
} ;
$r++ ;
} ;
print '</row>' ." " ;
} ;
$i++ ;
} ;
print "</document> " ;


 
 
To comment, please login or create a login
535 Chestnut Street - Suite 241 - Chattanooga TN 37402
423-605-6943