vavz has asked for the wisdom of the Perl Monks concerning the following question:
As I am new to Perl, I need to write a Perl script which converts csv to xml.
sample csv:
Current script:Name,Company,Email,Phone A,X,a.x@aol.com,1111 B,Y,b.y@aol.com,0 C,Z,c.z@aol.com,2222
I get after running the above:use strict; use warnings; use XML::Writer; use IO::File; use Data::Dumper; my $CSVfile="1.csv"; my $xmlFile="1.xml"; print "Input Csv file: $CSVfile and Output XML: $xmlFile\n"; my $output = IO::File->new(">$xmlFile"); my $writer = XML::Writer->new( OUTPUT => $output, DATA_MODE => 'true', UNSAFE => 1, DATA_INDENT => 6 ); $writer->xmlDecl("UTF-8"); my $rootTag="row"; my ($arrRef,$keys)= convertCsvToHash($CSVfile); for my $hash(@$arrRef){ writeXML($writer,$hash,$rootTag); } $writer->end(); $output->close(); sub writeXML{ my ($writer,$hash, $tagname, %attrs) = @_; $writer->startTag( $tagname, %attrs ); if (ref $hash eq "HASH" ){ for my $key(@$keys){ writeXML($writer,$hash->{$key},$key); } }else{ $writer->characters($hash); } $writer->endTag($tagname); } sub convertCsvToHash{ my $file = shift; open(FILE, "$file"); my @arr = <FILE>; close(FILE); my @hashArry; chomp($arr[0]); my @keys = split(',',$arr[0]); my @ke=my ($key1, $key2) = @keys[1,3]; for my $i(1..$#arr){ chomp($arr[$i]); my @splitRec = split(',',$arr[$i]); my $hash = {}; push (my @push, ($splitRec[1],$splitRec[3])); if ($push[1] ne 0) { for my $j(0..$#ke){ $hash->{$ke[$j]} = $push[$j]; } push @hashArry,$hash; } } return \@hashArry, \@ke; }
Expected ouput:<?xml version="1.0" encoding="UTF-8"?> <row> <Company>X</Company> <Phone>1111</Phone> </row> <row> <Company>Z</Company> <Phone>2222</Phone> </row>
Any help would be greatly appreciated, thanks<?xml version="1.0"?> <!DOCTYPE reference PUBLIC "-/EN" "reference.dtd"> <reference id="desc"> <title>Sample XML</title> <refbody> <section id="section_1"> <p> </p> <table id="table_1"> <tgroup cols="4"><colspec colnum="1" colname="col1" colwidth +="1.00*"/><colspec colnum="2" colname="col2" colwidth="1.00*"/> <thead> <row> <entry colname="col1">Company</entry> <entry colname="col2">Phone</entry> </row> </thead> <tbody> <row> <entry colname="col1">X</entry> <entry colname="col2">1111</entry> </row> </tbody> <tbody> <row> <entry colname="col1">Z</entry> <entry colname="col2">222</entry> </row> </tbody> </tgroup> </table> </section> </refbody> </reference>
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: csv to xml
by Marshall (Canon) on Aug 06, 2016 at 01:06 UTC | |
by Not_a_Number (Prior) on Aug 06, 2016 at 10:28 UTC | |
by Laurent_R (Canon) on Aug 06, 2016 at 12:49 UTC | |
by Not_a_Number (Prior) on Aug 06, 2016 at 13:46 UTC | |
by Marshall (Canon) on Aug 06, 2016 at 17:06 UTC | |
Re: csv to xml
by InfiniteSilence (Curate) on Aug 07, 2016 at 02:47 UTC |
Back to
Seekers of Perl Wisdom