2009-10-23 56 views
-4

我有有如何使用Perl解析XML?

<Doc> 
<Text> 
.... 
</Text> 
</Doc> 
<Doc> 
<Text> 
</Text> 
</Doc> 

文件如何只提取<text>元素,對它們進行處理,然後有效地提取下一文本元素?

我不知道我有多少個文件?

+0

看看http://stackoverflow.com/questions/487213/whats-the-best-xml-parser-for-perl另一Perl xml解析器的答案。 – 2009-10-23 23:48:30

回答

7

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 
} 
+0

如果我不知道我在文件中有多少個,我該如何使用它?謝謝。 – unj2 2009-10-23 23:20:01

+0

我得到一個不匹配的標籤錯誤...你知道這意味着什麼嗎? – unj2 2009-10-23 23:27:23

+0

使用Data :: Dumper; print Dumper($ data); – 2009-10-23 23:28:41

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>