【问题标题】:How can I parse XML using Perl?如何使用 Perl 解析 XML?
【发布时间】:2009-10-23 23:07:27
【问题描述】:

我有一个文件,其中有

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

如何仅提取 &lt;text&gt; 元素,对其进行处理,然后有效地提取下一个文本元素?

我不知道我在一个文件中有多少?

【问题讨论】:

标签: xml perl


【解决方案1】:
#!/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>

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

    • 如果我不知道一个文件中有多少个,我将如何使用它?谢谢。
    • 我得到一个不匹配的标签错误...你知道这是什么意思吗?
    • 使用数据::Dumper;打印转储器($data);
    • @kunjaan:您的 xml 无效。您可以将其保存到文件并在 IE 中打开以查看它是否有效
    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2011-03-25
    • 1970-01-01
    • 2017-10-28
    • 2012-05-05
    相关资源
    最近更新 更多