我正在处理从合作伙伴处收到的 XML 文件。我对更改此 xml 文件的构成没有任何影响。 XML 的摘录是:
<?xml version="1.0" encoding="UTF-8"?>
<objects>
<object>
<id>VW-XJC9</id>
<name>Name</name>
<type>House</type>
<description>
<![CDATA[<p>some descrioption of the house</p>]]> </description>
<localcosts>
<localcost>
<type>mandatory</type>
<name>What kind of cost</name>
<description>
<![CDATA[Some text again, different than the first tag]]>
</description>
</localcost>
</localcosts>
</object>
</objects>
我使用 Twig 的原因是这个 XML 大约有 11GB 大,大约有 100000 个不同的对象)。问题是当我到达 localcosts 部分时,跳过了 3 个字段(类型、名称和描述),可能是因为这些名称之前已经使用过。
我用来遍历xml文件的代码如下:
my $twig= new XML::Twig( twig_handlers => {
id => \&get_ID,
name => \&get_Name,
type => \&get_Type,
description => \&get_Description,
localcosts => \&get_Localcosts
});
$lokaal="c:\\temp\\data3.xml";
getstore($xml, $lokaal);
$twig->parsefile("$lokaal");
sub get_ID { my( $twig, $data)= @_; $field[0]=$data->text; $twig->purge; }
sub get_Name { my( $twig, $data)= @_; $field[1]=$data->text; $twig->purge; }
sub get_Type { my( $twig, $data)= @_; $field[3]=$data->text; $twig->purge; }
sub get_Description { my( $twig, $data)= @_; $field[8]=$data->text; $twig->purge; }
sub get_Localcosts{
my ($t, $item) = @_;
my @localcosts = $item->children;
for my $localcost ( @localcosts ) {
print "$field[0]: $localcost->text\n";
my @costs = $localcost->children;
for my $cost (@costs) {
$Type =$cost->text if $cost->name eq q{type};
$Name =$cost->text if $cost->name eq q{name};
$Description=$cost->text if $cost->name eq q{description};
print "Fields: $Type, $Name, $Description\n";
}
}
$t->purge;
}
当我运行这段代码时,主要字段的读取没有问题,但是当代码到达“localcosts”部分时,第二个 for-next 循环没有执行。当我将 xml 中的字段名称更改为唯一的名称时,此代码可以完美运行。
有人可以帮帮我吗?
谢谢
最佳答案
如果您希望类型、名称和描述的处理程序仅在对象标记中触发,请指定路径:
my $twig = new XML::Twig( twig_handlers => {
id => \&get_ID,
'object/name' => \&get_Name,
'object/type' => \&get_Type,
'object/description' => \&get_Description,
localcosts => \&get_Localcosts
});
关于xml - Perl,XML::Twig,如何读取具有相同标签的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106901/