
mirod
New User
May 27, 2011, 12:19 AM
Post #3 of 4
(7245 views)
|
Re: [rafay] Need to get (Key,Value) from XML based on previous element (Key,Value) data
[In reply to]
|
Can't Post
|
|
First, the INVOICE elements need to be wrapped in a root element, or the XML will not be well-formed. Once that's done, the following code will do the job. A couple of comments: to parse a file you will need to replace the call to parse by parsefile, your numbers are formatted the "European" way (with a comma before the decimal part), which is not the way Perl likes its numbers, so you need to convert them. Making the code robust is left as an exercise to the reader, since I can't really make assumptions about what is likely to go wrong with the data. I hope that helps.
#!/usr/bin/perl use strict; use warnings; use XML::Twig; my $total_for_date= get_total_amount( '20110402'); print "$total_for_date\n"; sub get_total_amount { my( $date)= @_; my $total=0; # long line below, feel free to break it up! XML::Twig->new( twig_handlers=> { qq{INVOICE[\@INVOICEDATE="$date"]} => sub { $total += att_to_nb($_->first_child( 'TOTALAMTINTAX')->att( 'TOTALAMOUNT')); } }) ->parse( \*DATA); return $total; } sub att_to_nb { my( $att)= @_; $att=~ s{,}{.}; return $att; } __DATA__ <invoices> <INVOICE INVOICENUMBER="007" INVOICEDATE="20110302" > <TOTALAMTINTAX TOTALAMOUNT="1,27 "/> </INVOICE> <INVOICE INVOICENUMBER="008" INVOICEDATE="20110402"> <TOTALAMTINTAX TOTALAMOUNT="1,47 "/> </INVOICE> <INVOICE INVOICENUMBER="009" INVOICEDATE="20110402"> <TOTALAMTINTAX TOTALAMOUNT="5,27 "/> </INVOICE> <INVOICE INVOICENUMBER="010" INVOICEDATE="20110502"> <TOTALAMTINTAX TOTALAMOUNT="6,27 "/> </INVOICE> </invoices>
|