I have a fi开发者_如何学运维le which has
<Doc>
<Text>
....
</Text>
</Doc>
<Doc>
<Text>
</Text>
</Doc>
How do I extract only the <text>
elements, process them and then extract the next text element efficiently?
I do not know how many I have in a file?
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $t = XML::Twig->new(
twig_roots => {
'Doc/Text' => \&print_n_purge,
});
$t->parse(\*DATA);
sub print_n_purge {
my( $t, $elt)= @_;
print $elt->text;
$t->purge;
}
__DATA__
<xml>
<Doc>
<Text>
....
</Text>
</Doc>
<Doc>
<Text>
</Text>
</Doc>
</xml>
XML::Simple can do this easily:
## make sure that there is some kind of <root> tag
my $xml_string = "<root><Doc>...</Doc></root>";
my $xml = XML::Simple->new();
$data = $xml->XMLin($xml_string);
for my $text_node (@{ $data->{'Doc'} }) {
print $text_node->{'Text'},"\n"; ## prints value of Text nodes
}
精彩评论