-4

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?

unj2
  • 52,135
  • 87
  • 247
  • 375
  • Take a look at http://stackoverflow.com/questions/487213/whats-the-best-xml-parser-for-perl for another Perl xml parser answer. – Robert P Oct 23 '09 at 23:48

2 Answers2

8
#!/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>
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
7

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
}
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82