Stoping xml parsing when a particular element is found
I have an xml which needs to be parsed. my
$parser = new XML::Parser开发者_StackOverflow中文版(Handlers =>
{Init => \&handle_Init, Start => \&handle_Start,
Char => \&handle_Char, End =>\&handle_End,
Final => \&handle_Final});
$parser->parsefile("ababab.xml");
In the handle_Char subroutine , as soon as I find a particular tag and its value, I want to stop.
How is it possible to achieve it?
You can wrap the call to parsefile in an eval and then die in the handler. You will then need to test $@ to see if parsing succeeded
An example:
#!/usr/bin/perl
use strict;
use warnings;
use XML::Parser;
my $p = XML::Parser->new(Handlers => { End => sub { if( $_[1] eq 'e') { die "ok"; } } });
print "parsing well-formed xml: ";
eval { $p->parse( '<d><b/><e/></d>'); };
if( $@ =~ m{^ok} ) { print "success\n"; } else { print $@; }
print "parsing malformed xml: ";
eval { $p->parse( '<d<b/><e/></d>'); };
if( $@ =~ m{^ok} ) { print "success\n"; } else { print $@; }
That said I would not use XML::Parser. The Perl5 wiki has a list of recommended modules for XML parsing.
精彩评论