使用我的代码,Perl :: Twig缺少一个父节点?

时间:2012-07-23 13:13:22

标签: xml perl perl-module xmlnode xml-twig

我不确定我的代码是否有问题,或者XML :: Twig 3.40是否存在问题。 目标是“更改或添加” 方法=“MODIF”节点“attributez”的父级

file input.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <world id="0" method="create">
     <continent id="0">
        <country id="18" method="create">
           <attributez>
              <info1>blabla</info1>
              <info2>blibli</info2>
           </attributez>
        </country>
     </continent>
   <attributez>
        <number_people>5billions</number_people>
        <number_continent>5</number_continent>
   </attributez>

     <oceans id="atlantic" method="create">
        <attributez>
           <name>ATLANTIC</name>
        </attributez>
     </oceans>

  </world>

我的代码(轻微修改自http://xmltwig.org/xmltwig/tutorial/yapc_twig_s4.html,例4):

#!/bin/perl -w
use strict;
use XML::Twig;

my $twig= new XML::Twig( 
            twig_handlers =>                  # player will be called
              { attributez => \&player }         
                   );                        

$twig->parsefile( "input.xml");                     # build the twig
$twig->flush;                                     # flush the end of the twig  

sub player
{ my( $twig, $valeur)= @_;                      # handlers params are always
                                              # the twig and the element

($valeur-> parent)   ->set_att("method" => "MODIF");

$twig->flush;                                 # flush the twig so far   
}

我们应该像这样更新root:

 <world id="0" method="MODIF">

相反,我们得到以下输出(根属性根本没有更新):

<?xml version="1.0" encoding="UTF-8"?>
<world id="0" method="create">
 <continent id="0">
    <country id="18" method="MODIF">
        <attributez>
            <info1>blabla</info1>
            <info2>blibli</info2>
        </attributez>
    </country>
</continent>

<attributez>
    <number_people>5billions</number_people>
    <number_continent>5</number_continent>
</attributez>

  <oceans id="atlantic" method="MODIF">
    <attributez>
        <name>ATLANTIC</name>
    </attributez>
  </oceans>
</world>

1 个答案:

答案 0 :(得分:0)

我必须删除最后一个(子程序播放器中的那个)

 $twig->flush;

现在输出正常