tags:

views:

206

answers:

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?

+4  A: 

Take a look at XML::Simple.

It makes looking through XML as simple as walking a hash.

Daren Schwenke
+4  A: 

Using a Perl XML parsing module would save you a bit of work:

Perl-XML module list

John at CashCommons
+6  A: 
#!/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
+5  A: 

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
What if I didn't know how many <Doc> I had in a file, how would I use it? Thanks.
kunjaan
And I get a mismatched tag error...do you know what that means?
kunjaan
use Data::Dumper;print Dumper($data);
Daren Schwenke
@kunjaan: your xml is not valid. You can save it to file and open in IE for example to see if it's valid
Ivan Nevostruev