gpt4 book ai didi

xml - 为什么 XML::Twig 不调用我的 end_tag_handler?

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

我尝试为每个标签调用子例程,但是 end_tag_handlers永远不会被调用。
我的目标是这个序列:

---顺序---
什么时候<auto>调用\&loading .
什么时候<apps><title>调用\&kicks .
什么时候<apps><logs>调用\&bye .
什么时候<apps>调用\&app .
什么时候<apps><title>调用\&kicks .
什么时候<apps><logs>调用\&bye .
什么时候<apps>调用\&app .
什么时候</auto>调用\&finish . → 它没有被调用。

临时文件:

#!/usr/local/bin/perl -w

use XML::Twig;
my $twig = XML::Twig->new(
start_tag_handlers =>
{ 'auto' => \&loading
},
twig_handlers =>
{ 'apps/title' => \&kicks,
'apps/logs' => \&bye
},
twig_roots =>
{ 'apps' => \&app
},
end_tag_handlers =>
{ 'auto' => \&finish
}
);
$twig -> parsefile( "doc.xml");

sub loading {
print "---loading--- \n";
}

sub kicks {
my ($twig, $elt) = @_;
print "---kicks--- \n";
print $elt -> text;
print " \n";
}

sub app {
my ($twig, $apps) = @_;
print "---app--- \n";
print $apps -> text;
print " \n";
}

sub bye {
my ($twig, $elt) = @_;
print "---bye--- \n";
print $elt->text;
print " \n";
}

sub finish {
print "---fishish--- \n";
}

doc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<auto>
<apps>
<title>watch</title>
<commands>set,start,00:00,alart,end</commands>
<logs>csv</logs>
</apps>
<apps>
<title>machine</title>
<commands>down,select,vol_100,check,line,end</commands>
<logs>dump</logs>
</apps>
</auto>

输出:

C:\>perl temp.pl
---loading---
---kicks---
watch
---bye---
csv
---app---
watchset,start,00:00,alart,endcsv
---kicks---
machine
---bye---
dump
---app---
machinedown,select,vol_100,check,line,enddump

我想要更多。

---finish---

最佳答案

来自 XML::Twig 的文档:

end_tag_handlers

A hash { expression => \&handler}. Sets element handlers that are called when the element is closed (at the end of the XML::Parser End handler). The handlers are called with 2 params: the twig and the tag of the element.

twig_handlers are called when an element is completely parsed, so why have this redundant option? There is only one use for end_tag_handlers: when using the twig_roots option, to trigger a handler for an element outside the roots.

您正在为作为根的 auto 元素设置结束处理程序。并且您仅将 twig_roots 用于 apps。因此永远不会调用结束处理程序。

您应该使用 twig_handlers 安装您的处理程序。

那么试试这个:

my $twig = XML::Twig->new(
start_tag_handlers =>
{ 'auto' => \&loading
},
twig_handlers =>
{ 'apps/title' => \&kicks,
'apps/logs' => \&bye,
'auto' => \&finish
},
twig_roots =>
{ 'apps' => \&app
},
);

关于xml - 为什么 XML::Twig 不调用我的 end_tag_handler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1452391/

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