|
Posted by Jordi Bernabeu (w00dy) on October 17, 2005, 7:57 pm
Please log in for more thread options
Henry Law wrote:
> [...]
> Here's a sample program; what it's intended to do is to pull out the
> "bkfile" element which has dbid=392; it does that, but pulls out much
> else besides - including the other bkfile element whose dbid doesn't
> match - and I can't find out what I'm doing wrong. All help very
> gratefully received. XML::Twig is a great module and I've used it
> extensively elsewhere; it would be a nuisance to have to use some other
> XML module for this task.
>
> This is XML::Twig 3.20 running under ActiveState Perl v5.8.7 and Windows
> XP (fully patched).
>
> -------------- sample program -------------
> use strict;
> use warnings;
>
> use XML::Twig;
>
> my $xmldoc = new XML::Twig;
> my $xmlsource =<<"ENDXML";
> <bkdirectory>
> <bkfile>
> <dbid>393</dbid>
> <b_size>177</b_size>
> </bkfile>
> <bkfile>
> <dbid>392</dbid>
> <b_size>460</b_size>
> </bkfile>
> </bkdirectory>
> ENDXML
>
> $xmldoc->parse($xmlsource);
>
> my @bkfiles = $xmldoc->get_xpath('//bkfile[string(dbid)="392"]]');
>
> print "\@bkfiles has ",scalar @bkfiles," elements\n\n";
> foreach my $elt (@bkfiles) {
> print "----",$elt->name,"\n";
> $elt->print;
> print "\n";
> }
Hi,
Have you tried using TwigHandlers when creating $xmldoc?
With get_xpath() you get the whole parent-tree (up to the root, hence
you get the whole document).
Try putting your xpath in TwigHandlers and your processing in a sub,
like this:
--------------------------- sample program -------------------
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $xmlsource =<<"ENDXML";
<bkdirectory>
<bkfile>
<dbid>393</dbid>
<b_size>177</b_size>
</bkfile>
<bkfile>
<dbid>392</dbid>
<b_size>460</b_size>
</bkfile>
</bkdirectory>
ENDXML
my $xmldoc = new XML::Twig( TwigHandlers =>
{
'bkfile[string(dbid)="392"] => \&process
}
);
$xmldoc->parse($xmlsource);
sub process
{
my ($twig, $element) = @_;
print $element->name,"\n";
foreach my $child ($element->children)
{
print $child->name,": ",$child->text,"\n";
}
}
--------------------- /sample program ----------------------------
Hope this helps.
Jordi (w00dy)
|