<Doc>
<Text>
....
</Text>
</Doc>
<Doc>
<Text>
</Text>
</Doc>
文件如何只提取<text>
元素,對它們進行處理,然後有效地提取下一文本元素?
我不知道我有多少個文件?
<Doc>
<Text>
....
</Text>
</Doc>
<Doc>
<Text>
</Text>
</Doc>
文件如何只提取<text>
元素,對它們進行處理,然後有效地提取下一文本元素?
我不知道我有多少個文件?
XML::Simple可以很容易地做到這一點:
## 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
}
#!/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>
看看http://stackoverflow.com/questions/487213/whats-the-best-xml-parser-for-perl另一Perl xml解析器的答案。 – 2009-10-23 23:48:30