0

有一个 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;
    }
4

1 回答 1

0

I'm going to assume when you say "every element" you mean it. There's several ways you can do that via twig_handlers. There is the special handler _all_. Or since twig_handler keys are XPath expressions you can use *.

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 回答