这里有一个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;
}发布于 2012-10-21 02:51:38
我假设当你说“每个元素”时,你是认真的。有几种方法可以通过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;https://stackoverflow.com/questions/12982590
复制相似问题