in reply to CSV to XML

G'day fmcroft92,

Welcome to the Monastery.

[I appreciate this is your first post here; however, there are some issues with what you've presented. You should provide a small, representative example of your input and the output you would expect from that. See "How do I post a question effectively?" for more details about that. URLs should be provided as links, not plain text — "What shortcuts can I use for linking to other information?" has details on how to achieve that. I followed the URL you provided but only found links to a variety of examples and you had not shown any indication which of these would be appropriate: I wasn't prepared to hunt around and make guesses — it would have been better to use the sample output for this or, if there was detailed information, a direct link to whatever you're working with. The whole idea is for you to do sufficient up-front work so we aren't left making assumptions about what you want; the end result being that you get better answers, and get them a lot more quickly. Please understand that this is not a rebuke but purely information: just keep it in mind for any future posts.]

I put together the following script to give you an example of the type of code you may need.

#!/usr/bin/env perl use strict; use warnings; use autodie; use Text::CSV; use XML::LibXML; my $csv_file = 'pm_11132234_input.csv'; my $xml_file = 'pm_11132234_output.xml'; my $xml = XML::LibXML::Document::->new(); my %element_for_header = qw{Name name Example value}; { my $csv = Text::CSV::->new(); open my $csv_fh, '<', $csv_file; my @elements = map $element_for_header{$_}, @{$csv->getline($csv_f +h)}; my $csv_element = $xml->createElement('csv'); while (my $row = $csv->getline($csv_fh)) { my $row_element = $xml->createElement('row'); for my $i (0 .. $#elements) { my $node = $xml->createElement($elements[$i]); $node->appendText($row->[$i]); $row_element->addChild($node); } $csv_element->addChild($row_element); } $xml->addChild($csv_element); } $xml->toFile($xml_file, 1); # Just for testing print "*** $csv_file ***\n"; system cat => $csv_file; print "*** $xml_file ***\n"; system cat => $xml_file;

Output:

*** pm_11132234_input.csv *** Name,Example plain,abc ampersand,x&y *** pm_11132234_output.xml *** <?xml version="1.0"?> <csv> <row> <name>plain</name> <value>abc</value> </row> <row> <name>ampersand</name> <value>x&amp;y</value> </row> </csv>

Notes:

— Ken