-3

I'm trying to parse a csv file and convert it to XML. The .csv file consists of a list of entries, separated by commas. So, two sample entries look like this:

AP,AB,A123,B123,,,
MA,NA,M123,TEXT,TEXT,TEXT_VALUE

Some field are blank in file and file has no header rows. Any suggestions how to go with this. Haven't figured out how to go with this. Thanks.

  • 3
    Read it using [Text::CSV](http://search.cpan.org/~ishigaki/Text-CSV-1.91/lib/Text/CSV.pm), then write an xml file using a module for that. For instance, [XML::LibXML](http://search.cpan.org/dist/XML-LibXML/LibXML.pod), where you'll use [XML::LibXML::Document](http://search.cpan.org/dist/XML-LibXML/lib/XML/LibXML/Document.pod). There are other modules, [XML::Twig](http://search.cpan.org/~mirod/XML-Twig-3.49/Twig.pm) in the first place. The [XML::Writer](http://search.cpan.org/dist/XML-Writer/Writer.pm) used to be popular but I don't know much about it nor its standing now. – zdim Feb 14 '17 at 05:06
  • 2
    You'll need to come up with _how_ you want your data organized, ie. how your xml is going to look. As for writing with `XML::LibXML`, here is a possibly useful [SO post](http://stackoverflow.com/a/2934794/4653379), and another [PerlMonks post](http://www.perlmonks.org/?node_id=1026789) (these links didn't fit in the above comment). – zdim Feb 14 '17 at 05:09
  • 1
    It's not hard to do, but XML is a lot more complicated than CSV. So at the very least we'll need an idea of what your XML should look like. – Sobrique Feb 14 '17 at 09:29

1 Answers1

5
print "<myXML>\n";
while (<>) {
  print "<aRow>$_</aRow>\n";
}
print "</myXML>\n";

Or, using XML::LibXML, something like this:

#!/usr/bin/perl

use strict;
use warnings;

use XML::LibXML;

my $doc = XML::LibXML::Document->createDocument;

my $root = $doc->createElement('myXML');
$doc->setDocumentElement($root);
$root->appendChild($doc->createTextNode("\n"));

while (<>) {
  chomp;
  my $row = $doc->createElement('aRow');
  $root->appendChild($row);
  $row->appendChild($doc->createTextNode($_));
  $root->appendChild($doc->createTextNode("\n"));
}

print $doc->toString;

Of course, if you told us what the output should look like, we could probably come up with something a little more sophisticated!

Dave Cross
  • 68,119
  • 3
  • 51
  • 97