首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向所有元素添加递增的id属性

向所有元素添加递增的id属性
EN

Stack Overflow用户
提问于 2012-10-20 05:17:40
回答 1查看 211关注 0票数 0

这里有一个XML-Twig示例,它展示了如何向指定的元素添加具有递增值的id属性。有没有简单的方法将递增的id添加到所有元素中。

代码语言:javascript
复制
#!/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;
    }
EN

回答 1

Stack Overflow用户

发布于 2012-10-21 02:51:38

我假设当你说“每个元素”时,你是认真的。有几种方法可以通过twig_handlers做到这一点。这里有一个特殊的处理程序_all_。或者,因为twig_handler键是XPath表达式,所以可以使用*

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12982590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档