简体   繁体   中英

perl script to print xml file data

How to print multiple number of trouble code and descripions using perl script.I have the xml file like this..

 <data>........
        .......
      </data>

lik this i have more number of trouble codes.still now i am printing only trouble code,how should i print descrption below the trouble code.

Try this:

#!/C:/Languages/Perl64/bin/perl.exe

use warnings;
use strict;
use XML::LibXML::Reader;

my $file;
open( $file, 'test.xml' );
my $reader = XML::LibXML::Reader->new( IO => $file ) or die( "unable to open file" );
while ( $reader->nextElement( 'DTC' ) ) {
    my $description = $reader->readOuterXml();
    $reader->nextElement( 'TroubleCode' );
    my $troubleCode = $reader->readInnerXml();
    print( "trouble code: $troubleCode\n" );
    print( " description: $description\n" );
}
close( $file );

Okay, corrected and tested. This works per your question.

I answered the same question over on perlmonks so hopefully he finds an answer he likes.

use XML::Simple;
my $xml = new XML::Simple;

my $data = $xml->XMLin("data.xml");

my %by_code;
foreach my $dtc ( @{ $data->{DTC} } ) {
    push @{ $by_code{ $dtc->{TroubleCode} } }, $dtc;
}

foreach my $code ( sort { $a <=> $b } keys %by_code ) {
    print "trouble code: $code\n";
    print "description:\n";
    print map { $xml->XMLout( $_, RootName => 'DTC', NoAttr => 1, ) }
        @{ $by_code{$code} };
}

Would you try this:

 print " DTCnumber: \n" . join("\n", @dtcnumber);

and:

print " DTCdes: \n" .  join("\n", @dtcdes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM