如何使用XML :: Twig获得内容? [英] How can I get content using XML::Twig?
问题描述
我的目标是start_tag_handler
(请参见下文)在找到apps
/title
标记时获得apps
/title
内容(请参见下面的示例XML).
My aim is that start_tag_handler
(see below) get the apps
/title
content when it finds an apps
/title
tag (see sample XML below).
然后
end_tag_handler
在找到apps
/logs
标记时获得apps
/logs
内容.
And
end_tag_handler
gets the apps
/logs
content when it finds an apps
/logs
tag.
但是此代码返回null并退出.
But instead this code returns null and exits.
#!/usr/local/bin/perl -w
use XML::Twig;
my $twig = XML::Twig->new(
start_tag_handlers =>
{ 'apps/title' => \&kicks
},
twig_roots =>
{ 'apps' => \&app
},
end_tag_handlers =>
{ 'apps/logs' => \&bye
}
);
$twig -> parsefile( "doc.xml");
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";
}
这是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 parse.pl
---kicks---
---app---
watchset,start,00:00,alart,endcsv
---kicks---
---app---
machinedown,select,vol_100,check,line,enddump
推荐答案
Check out the XML::Twig
documentation for start_tag_handlers
:
用两个参数调用处理程序:树枝和元素.此时该元素为空,尽管已创建其属性.
The handlers are called with 2 params: the twig and the element. The element is empty at that point, its attributes are created though.
在调用start_tag_handlers
时,甚至还看不到文本内容,因为解析了开始标签(例如,<title>
,而不是结束标签</title>
)才刚刚完成.
At the time start_tag_handlers
is called, the text content isn't even seen yet, since parsing of the start tag (e.g. <title>
, not the end tag </title>
) has only just completed.
end_tag_handlers
不提供元素文本的原因可能是出于对称性:-).
The reason that end_tag_handlers
don't supply element text is probably for symmetry :-).
您想要的可能是使用twig_handlers
代替:
What you want is probably to use twig_handlers
instead:
my $twig = XML::Twig->new(
twig_handlers => {
'apps/title' => \&kicks,
'apps/logs' => \&bye
},
twig_roots => {
'apps' => \&app
},
);
输出为:
---kicks---
watch
bye
csv
---app---
watchset,start,00:00,alart,endcsv
---kicks---
machine
bye
dump
---app---
machinedown,select,vol_100,check,line,enddump
这篇关于如何使用XML :: Twig获得内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!