加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 如何使用XML :: Twig的处理程序传递参数并返回值?

发布时间:2020-12-16 06:25:43 所属栏目:大数据 来源:网络整理
导读:我的问题是:如何将一些参数传递给 XML:Twig的处理程序,以及如何从处理程序返回结果. 这是我的代码,硬编码: counter name =“music”,report type =“month”,stringSet index = 4. 如何通过使用参数$counter_name,$type,$id来实现这一点?以及如何返回str
我的问题是:如何将一些参数传递给 XML:Twig的处理程序,以及如何从处理程序返回结果.

这是我的代码,硬编码:

< counter name =“music”,report type =“month”,stringSet index = 4>.

如何通过使用参数$counter_name,$type,$id来实现这一点?以及如何返回string_list的结果?谢谢(抱歉,我没有在这里发布xml文件,因为我遇到了一些麻烦.<和>中的任何内容都被忽略了).

use XML::Twig;

sub parse_a_counter {

     my ($twig,$counter) = @_;
     my @report = $counter->children('report[@type="month"]');

     for my $report (@report){

         my @stringSet = $report->children('stringSet[@index=”4”]');
         for my $stringSet (@stringSet){

             my @string_list = $stringSet->children_text('string');
             print @string_list;  #  in fact I want to return this string_list,#  not just print it.
         }
     }

     $counter->flush; # free the memory of $counter
}

my $roots = { 'counter[@name="music"]' => 1 };

my $handlers = { counter => &;parse_a_counter };

my $twig = new XML::Twig(TwigRoots => $roots,TwigHandlers => $handlers);

$twig->parsefile('counter_test.xml');

解决方法

将参数传递给处理程序的最简单,通常的方法是使用闭包.这是一个很大的词,但是一个简单的概念:你称这个处理程序就像这个tag => sub {handler(@_,$my_arg)}和$my_arg将传递给处理程序. Achieving Closure对该概念有更详细的解释.

以下是我编写代码的方法.我使用Getopt :: Long进行参数处理,并使用qq {}代替包含XPath表达式的字符串的引号,以便能够在表达式中使用引号.

#!/usr/bin/perl
use strict;
use warnings;

use XML::Twig;

use Getopt::Long;

# set defaults
my $counter_name= 'music';
my $type= 'month';
my $id= 4;

GetOptions ( "name=s" => $counter_name,"type=s" => $type,"id=i"   => $id,) or die;   

my @results;

my $twig= XML::Twig->new( 
            twig_roots => { qq{counter[@name="$counter_name"]} 
                             => sub { parse_a_counter( @_,$id,@results); } } )
                   ->parsefile('counter_test.xml');

print join( "n",@results),"n";

sub parse_a_counter {

     my ($twig,$counter,$results) = @_;
     my @report = $counter->children( qq{report[@type="$type"]});

     for my $report (@report){

         my @stringSet = $report->children( qq{stringSet[@index="$id"]});
         for my $stringSet (@stringSet){

             my @string_list = $stringSet->children_text('string');
             push @$results,@string_list;
         }
     }

     $counter->purge; # free the memory of $counter
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读