xmlperlsax

How do I parse a file using Perl's XML::SAX?


I am trying XML::SAX parser for parsing XML file. XML file is shown below,

            <message>
                <c1>
                    <rrcConnectionSetupComplete>
                        <rrc-TransactionIdentifier>2</rrc-TransactionIdentifier>
                        <criticalExtensions>
                            <c1>
                                <rrcConnectionSetupComplete-r8>
                                    <selectedPLMN-Identity> 1 </selectedPLMN-Identity>
                                    <dedicatedInfoNAS> 07410109014290112345671000028020000f0 </dedicatedInfoNAS>
                                </rrcConnectionSetupComplete-r8>
                            </c1>
                        </criticalExtensions>
                    </rrcConnectionSetupComplete>
                </c1>
            </message>

Perl code is shown below,

use strict;

use XML::SAX;
use MySAXHandler;

my $parser = XML::SAX::ParserFactory->parser(Handler => MySAXHandler->new);

$parser->parse_uri("uL-DCCH-Message.xml");

my $rrc_trans_identifier = $parser->{'c1'}->{'rrcConnectionSetupComplete'}->{'rrc-TransactionIdentifier'};
print "rrc_trans_id :: $rrc_trans_identifier\n";

my $selected_plmn_id = $parser->{c1}->{rrcConnectionSetupComplete}->{criticalExtensions}->{c1}->{'rrcConnectionSetupComplete-r8'}->{'selectedPLMN-Identity'};
print "plmn identity :: $selected_plmn_id\n";

my $rrc_dedicated_info_nas = $parser->{c1}->{rrcConnectionSetupComplete}->{criticalExtensions}->{c1}->{'rrcConnectionSetupComplete-r8'}->{dedicatedInfoNAS};
print "dedicated info nas :: $rrc_dedicated_info_nas\n";

When i run this code, i am getting output as,

Can't locate MySAXHandler.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.0 /usr/local/share/perl/5.10.0 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .) at sax.pl line 4.
BEGIN failed--compilation aborted at sax.pl line 4.

I installed XML::SAX from CPAN, but still it shows some module missing error.

My questions are,

  1. Does it needs anyother modules to be installed?

  2. To access the values in XML file, the procedure i am following is correct?

For example:

my $rrc_trans_identifier = $parser->{'c1'}->{'rrcConnectionSetupComplete'}->{'rrc-TransactionIdentifier'};
print "rrc_trans_id :: $rrc_trans_identifier\n";

Solution

  • You need to write your own MySAXHandler (the clue is in the name!).

    See the SAX::Intro documentation for more details.

    Update: Replaced search.cpan.org link with metacpan.org.