From: Travis <[EMAIL PROTECTED]>
> Never written a line of Perl until now but I think it might be perfect
> for this little program I need.
> 
> I have some CSV files that are given to me and I need to spit them in
> a format that kind of looks like XML but I don't think it is. The
> structure looks something like this:
> 
> <ADDRESSES>
> <struct>
>     <field name="First" value="John" />
>     <field name="Last" value="Doe" />
>     <field name="City" value="San Francisco" />
> </struct><struct>
>     <field name="First" value="Jane" />
>     <field name="Last" value="Johnson" />
>     <field name="City" value="New York City" />
> </struct>
> </ADDRESSES>
> 
> 
> I don't think that's standard XML is it? If so please let me know so I
> can change my google searching on the topic.

It is proper XML.

Here is one possible solution:

use strict;
use IO::Handle;
use Text::CSV_XS;
use XML::Rules;

my $csv = Text::CSV_XS->new ({binary => 1});
my $xml = XML::Rules->new(rules=>[]);

my $headers = $csv->getline(\*DATA) or die "The file is not CSV!\n";

print "<ADDRESSES>\n";
while (my $row = $csv->getline(\*DATA)) {
        my @data;
        for my $i (0 .. $#$headers) {
                push @data, {name => $headers->[$i], value => $row->[$i]};
        }
        print '  ', $xml->ToXML(struct => {field => [EMAIL PROTECTED], 0, '  ', 
'  '), 
"\n";
}
print "</ADDRESSES>\n";


__END__
First,Last,City
John,Doe,San Francisco
Jane,Johnson,New York City


Unlike some suggestions at comp.lang.perl.misc this one is actually 
correct. That is it handles even more complex CSV and escapes data 
for XML correctly.

You may need to change the options for the Text::CSV_XS->new() 
constructor and you will want to read the data from a different 
filehandle than DATA (that's a special filehandle that allows you to 
read the part of the script after the __END__ marker).


The strange looking $#$headers is the count of elements in the array 
referenced by $headers. Just like $#array is the length of @array, 
$#$arrayref is the length ot @$arrayref.

Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to