Here is how I would approach this problem using XML::Twig.

This reads in the XML file, and for each 'Vehicle' element, calls a subroutine named 'vehicle'. This sub opens a new output file whose name is the value of 'AuctionID' (since that seems unique) with a '.csv' extension. It outputs a comma-separated header line, then a CSV line. I only showed 4 values, but you could easily extend the code to add more values, in the order you require. This could be something you can build upon.

The code creates 2 output files: 25019.csv and 25020.csv.

Note: the XML you posted is invalid because it is missing a closing 'Vehicle' tag.

use strict; use warnings; use XML::Twig; my $twig= new XML::Twig( twig_handlers => { Vehicle => \&vehicle } ); $twig->parsefile('in.xml'); exit; sub vehicle { my ($twig, $car) = @_; return if $car->first_child('Summary'); my $file = $car->first_child('AuctionID')->text() . '.csv'; open my $fh, '>', $file or die "can not open $file: $!"; print $fh "AuctionID,Ref,VehicleID,Manufacturer\n"; print $fh join ',' , $car->first_child('AuctionID' )->text() , $car->first_child('Ref' )->text() , $car->first_child('VehicleID' )->text() , $car->first_child('Manufacturer')->text() ; print $fh "\n"; close $fh; }

Here are the contents of output file 25019.csv:

AuctionID,Ref,VehicleID,Manufacturer 25019,1480714,156171,TOYOTA

Since some of your data does contain commas, it might be prudent to also use a CSV-type CPAN module such as Text::CSV_XS.


In reply to Re: Parse XML into CSV Files by toolic
in thread Parse XML into CSV Files by dmsparts

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.