Posted By

bionic on 03/03/10


Tagged

xml csv csv2xml


Versions (?)

csv2xml perl version


 / Published in: Perl
 

Useful perl snippet to convert csv docs to xml from Ankh on the freenode #xml irc channel

  1. #! /usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use Text::CSV;
  5.  
  6. # generate XML from CSV files
  7. #
  8.  
  9.  
  10. my $csv = Text::CSV->new(
  11. {
  12. binary => 1, # binary for utf8, latin1 etc
  13. sep_char => "\t"
  14. }
  15. ) or die "Cannot use CSV: ".Text::CSV->error_diag ();
  16.  
  17. $csv->eol("
  18. ");
  19.  
  20. binmode(STDIN, ":utf8");
  21. binmode(STDOUT, ":utf8");
  22.  
  23. foreach (@ARGV) {
  24. open my $input, "<:encoding(utf8)", $_ or die "test.csv: $!";
  25.  
  26. print "<csv filename=\"$_\">";
  27. while (my $colref = $csv->getline($input)) {
  28. print "<row>" .
  29. join("", map { "<cell>$_</cell>" } @$colref ) .
  30. "</row>\n";
  31. }
  32. print "</csv>\n";
  33. }

Report this snippet  

You need to login to post a comment.