2012-10-19 32 views
0

有一个XML-Twig示例显示如何将id属性与递增值一起添加到指定元素。是否有简单的方法将增加的id添加到所有元素。向所有元素添加递增的id属性

#!/bin/perl -w 

######################################################################### 
#                  # 
# This example adds an id to each player        # 
# It uses the set_id method, by default the id attribute will be 'id' # 
#                  # 
######################################################################### 

use strict; 
use XML::Twig; 

my $id="player001"; 

my $twig= new XML::Twig(twig_handlers => { player => \&player }); 
$twig->parsefile("nba.xml"); # process the twig 
$twig->flush; 
exit; 

    sub player 
    { my($twig, $player)= @_; 
     $player->set_id($id++); 
     $twig->flush; 
    } 
+0

*每个*元素,或每个''元素?你的代码对于后者是正确的,尽管你可能不想覆盖现有的ID。 – Schwern

回答

0

我打算假设你说“每个元素”是你的意思。有几种方法可以通过twig_handlers来完成。有特殊处理器_all_。或者由于twig_handler键是XPath表达式,所以可以使用*

use strict; 
use warnings; 
use XML::Twig; 

my $id="player001"; 
sub add_id { 
    my($twig, $element)= @_; 

    # Only set if not already set 
    $element->set_id($id++) unless defined $element->id; 

    $twig->flush; 
} 

my $twig= new XML::Twig(
    twig_handlers  => { 
     # Either one will work. 
     # '*'  => \&add_id, 
     '_all_' => \&add_id, 
    }, 
    pretty_print  => 'indented', 
); 
$twig->parsefile(shift); # process the twig 
$twig->flush; 
+0

是的,谢谢我的意思是每个元素自动,因为我不知道哪些元素被创建,因为脚本正在转换doxygen生成perl模块的C++ api,并且可能有也可能不是公共静态方法元素。 –