How do I use Perl's XML::Twig to count multiple tags in XML?
I am using XML::Twig to parse my input xml using Perl.
I need to extact a particular node in this XML and validate that node to see if it has multiple <p>
tags and then count words in those P tags.
For example:
<XML>
<name>
</name>
<address>
<p id="1">a b c d </p>
<p id=开发者_开发问答"2">y y y </p>
</address>
</XML>
Output:
Address has 2 paragraph tags with 7 words.
Any suggestions?
Here is one way to do it:
use strict;
use warnings;
use XML::Twig;
my $xfile = q(
<XML>
<name>
</name>
<address>
<p id="1">a b c d </p>
<p id="2">y y y </p>
</address>
</XML>
);
my $t = XML::Twig->new(
twig_handlers => { 'address/p' => \&addr}
);
my $pcnt = 0;
my $wcnt = 0;
$t->parse($xfile);
print "Address has $pcnt paragraph tags with $wcnt words.\n";
sub addr {
my ($twig, $add) = @_;
my @words = split /\s+/, $add->text();
$wcnt += scalar @words;
$pcnt++;
}
__END__
Address has 2 paragraph tags with 7 words.
XML::Twig has a dedicated website with documentation and a Tutorial to describe the handler technique used above.
精彩评论