I have a file 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?
I have a file 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?
Take a look at XML::Simple.
It makes looking through XML as simple as walking a hash.
Using a Perl XML parsing module would save you a bit of work:
#!/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
}