将递增的id属性添加到所有元素

时间:2012-10-19 21:17:40

标签: perl xml-twig

有一个XML-Twig示例显示如何将具有递增值的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;
    }

1 个答案:

答案 0 :(得分: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;