Perl,XML :: Twig,如何使用相同的标记读取字段
发布时间:2020-12-15 21:43:41 所属栏目:大数据 来源:网络整理
导读:我正在处理从合作伙伴处收到的 XML文件.我对更改此xml文件的构成没有任何影响. XML的摘录是: ?xml version="1.0" encoding="UTF-8"?objects object idVW-XJC9/id nameName/name typeHouse/type description ![CDATA[psome descrioption of the house/p]] /d
我正在处理从合作伙伴处收到的
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:tempdata3.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->textn"; 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,$Descriptionn"; } } $t->purge; } 当我运行这段代码时,主要字段被读取没有问题,但是当代码到达’localcosts’部分时,第二个for-next循环不会被执行.当我将xml中的字段名称更改为唯一的名称时,此代码可以正常工作. 有人可以帮我吗? 谢谢 解决方法
如果只希望在object标签中触发type,name和desctiption处理程序,请指定路径:
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 }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |