0

指定された要素に増分値を持つ id 属性を追加する方法を示す XML-Twig の例があります。インクリメントされた 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;
    }
4

1 に答える 1

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;
于 2012-10-20T18:51:37.550 に答える