【发布时间】:2011-05-16 13:41:01
【问题描述】:
部分 XML 如下所示:
<ipcEntry kind="1" symbol="A01B0013080000" ipcLevel="A" entryType="K" lang="EN" nocore="yes">
<textBody>
<title>
<titlePart>
<text>for working subsoil</text>
</titlePart>
</title>
</textBody>
<ipcEntry kind="2" symbol="A01B0013100000" ipcLevel="A" entryType="K" lang="EN" nocore="yes">
<textBody>
<title>
<titlePart>
<text>Special implements for lifting subsoil layers</text>
</titlePart>
</title>
</textBody>
<ipcEntry kind="3" symbol="A01B0013120000" ipcLevel="A" entryType="K" lang="EN" nocore="yes">
<textBody>
<title>
<titlePart>
<text>Means for distributing the layers on the surface</text>
</titlePart>
</title>
</textBody>
</ipcEntry>
</ipcEntry>
</ipcEntry>
我的代码是:
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
use Data::Dumper;
my $twig_handlers = { 'ipcEntry' => \&ipcEntrySub };
my $file = 'A01B.xml';
my $twig= new XML::Twig( twig_handlers => $twig_handlers );
$twig->parsefile($file);
#$twig->print;
sub ipcEntrySub {
my ($twig_obj, $element) = @_;
print $element->{'att'}->{'symbol'} . "\n";
print "Kind: $element->{'att'}->{'kind'}\n";
print $element->text . "\n";
print "###########################################\n";
$twig_obj->purge;
}
好像看不到文字:<text>Special implements for lifting subsoil layers</text>
我猜是因为<ipcEntry kind="2" symbol="A01B0013100000" ipcLevel="A" entryType="K" lang="EN" nocore="yes"> 有另一个子 ipcEntry。
我可以得到<text>Means for distributing the layers on the surface</text>。
我在这里做错了什么?
谢谢,
【问题讨论】:
-
您希望输出到底是什么?
-
基本上,打印其中的所有
元素,以及每个 的属性 -
清除时,会丢失当前元素之前的所有元素。您只需将元素的父元素保留为空,即您仍然可以访问它们的属性,但它们的所有内容都会丢失。所以确实 delete 是你想要的。
-
+1 mirod,我认为您的评论比我的回答要清楚得多。如果您可以在 XML::Twig Perl 文档中包含上述注释,那就太好了。我当然很困惑,我如何访问属性,而不是清除元素后的内容。也非常感谢出色的 XML::Twig。
标签: xml perl xml-parsing xml-twig