gpt4 book ai didi

xml - 为什么 XML::Twig 输出提取的字符串两次?

转载 作者:数据小太阳 更新时间:2023-10-29 02:20:09 27 4
gpt4 key购买 nike

为什么我的字符串在输出中出现两次?

#!/usr/bin/perl
use warnings;
use strict;

use XML::Twig;


my $string = '<cd_catalogue><title>Hello, World!</title></cd_catalogue>';

my $t= XML::Twig->new( twig_handlers => { cd_catalogue => \&cd_catalogue, },
pretty_print => 'indented',
);

$t->parse( $string );


sub cd_catalogue {
my( $t, $cd_catalogue ) = @_;
$cd_catalogue->flush;
}


# Output:
#<cd_catalogue>
# <title>Hello, World!</title>
#</cd_catalogue>
#<cd_catalogue>
# <title>Hello, World!</title>
#</cd_catalogue>

最佳答案

将您的 sub 更改为使用 printpurge 而不是 flush 解决问题:

sub cd_catalogue {
my( $t, $cd_catalogue ) = @_;
$cd_catalogue->print;
$cd_catalogue->purge;
}

由于示例的简单性,flush 变得困惑,因为 cd_catalogue 是根节点。如果您将数据更改为如下内容:

my $string = '
<cds>
<cd_catalogue><title>Hello, World!</title></cd_catalogue>
</cds>';

或者如果您更改了 twig_handler 以查找 title:

twig_handlers    => { title => \&cd_catalogue }

然后您会发现 $cd_catalogue->flush 现在可以与您的 $string 一起正常工作。

/I3az/

关于xml - 为什么 XML::Twig 输出提取的字符串两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2018967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com