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开发者_Go百科>
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);
精彩评论