in reply to XML::twig counting elements that don't have a certain attribute/value on them
I know you've said you use XML::Twig, but ... this solution has the additional advantage that it doesn't keep the whole parsed document in memory:
use strict; use warnings; no warnings 'uninitialized'; use XML::Rules; my $xmlStr = <<XML; <foo> <qp name="foo"> <q supp="yes">hello</q> <q supp="no">bye</q> <xr supp="yes">later</xr> </qp> <qp name="bar"> <q supp="yes">bye</q> <xr supp="no">later</xr> <xr supp="no">sometime</xr> </qp> </foo> XML my $parser = XML::Rules->new( stripspaces => 7, rules => { 'q,xr' => sub { return if $_[1]->{supp} eq 'yes' or $_[1]->{info} eq 'yes' +; return '+count' => 1; }, qp => sub { printf "Definition '%s' has %d quotations.\n", $_[1]->{nam +e}, $_[1]->{count}+0; return '+total' => $_[1]->{count}+0; }, foo => sub { return $_[1]->{total} }, _default => '', }, ); my $total = $parser->parse($xmlStr); print "The total count is $total\n";
Jenda
Enoch was right!
Enjoy the last years of Rome.
|
|---|