代码之家  ›  专栏  ›  技术社区  ›  tknv

为什么xml::twig不调用我的结束标记处理程序?

  •  3
  • tknv  · 技术社区  · 15 年前

    我尝试为每个标记调用子例程,但是 end_tag_handlers 从不调用。
    我的目标是一个这样的序列:

    ---序列---
    什么时候 <auto> 呼叫 \&loading .
    什么时候 <apps><title> 呼叫 \&kicks .
    什么时候 <apps><logs> 呼叫 \&bye .
    什么时候 <apps> 呼叫 \&app .
    什么时候 <应用程序标题 呼叫 踢腿 .
    什么时候 <应用程序日志 呼叫 再见 .
    什么时候 <Apps≫ 呼叫 应用程序 .
    什么时候 </auto> 呼叫 \&finish . 渐次 没有打电话。

    温度PL:

    #!/usr/local/bin/perl -w
    
    use XML::Twig;
    my $twig = XML::Twig->new(
                start_tag_handlers => 
                  { 'auto' => \&loading
                  },
                twig_handlers =>
                  { 'apps/title' => \&kicks,
                    'apps/logs' => \&bye
                  },
                twig_roots =>
                  { 'apps' => \&app
                  },
                end_tag_handlers => 
                  { 'auto' => \&finish
                  }
                );
    $twig -> parsefile( "doc.xml");
    
      sub loading {
        print "---loading--- \n";
      }
    
      sub kicks {
        my ($twig, $elt) = @_;
        print "---kicks--- \n";
        print $elt -> text;
        print " \n";
      }
    
      sub app {
        my ($twig, $apps) = @_;
        print "---app--- \n";
        print $apps -> text;
        print " \n";
      }
    
      sub bye {
      my ($twig, $elt) = @_;
      print "---bye--- \n";
      print $elt->text;
      print " \n";
      }
    
      sub finish {
        print "---fishish--- \n";
      }
    

    XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <auto>
      <apps>
        <title>watch</title>
        <commands>set,start,00:00,alart,end</commands>
        <logs>csv</logs>
      </apps>
      <apps>
        <title>machine</title>
        <commands>down,select,vol_100,check,line,end</commands>
        <logs>dump</logs>
      </apps>
    </auto>
    

    输出:

    C:\>perl temp.pl
    ---loading---
    ---kicks---
    watch
    ---bye---
    csv
    ---app---
    watchset,start,00:00,alart,endcsv
    ---kicks---
    machine
    ---bye---
    dump
    ---app---
    machinedown,select,vol_100,check,line,enddump  
    

    我想要更多的。

    ---finish---
    
    1 回复  |  直到 15 年前
        1
  •  6
  •   friedo    15 年前

    从文档中 XML::Twig :

    end_tag_handlers

    散列表达式=>\&handler。设置当元素 关闭(在xml::parser结束处理程序的末尾)。用2调用处理程序 参数:元素的细枝和标签。

    twig_handlers 当一个元素被完全解析时调用,那么为什么要有这个多余的 选择权?只有一种用途 结束标记处理程序 :使用时 twig_roots 选项,以 为根之外的元素触发处理程序。

    您正在为您的 auto 元素,它是根。你只是在使用 细根 对于 apps . 因此永远不会调用结束处理程序。

    您应该使用 Twitter处理器 相反。

    所以试试这个:

    my $twig = XML::Twig->new(
            start_tag_handlers => 
              { 'auto' => \&loading
              },
            twig_handlers =>
              { 'apps/title' => \&kicks,
                'apps/logs' => \&bye,
                'auto'      => \&finish
              },
            twig_roots =>
              { 'apps' => \&app
              },
            );