如何使用XML :: Twig获取内容?

时间:2009-09-19 03:26:15

标签: xml perl xml-twig

我的目标是start_tag_handler(见下文)在找到apps / title标记时获取apps / title内容(请参阅示例XML下文)。

end_tag_handler在找到apps / logs代码时会获得apps / logs个内容。

但是这段代码返回null并退出。

这是用于解析的Perl代码(使用XML::Twig)###:

    #!/usr/local/bin/perl -w

    use XML::Twig;
    my $twig = XML::Twig->new(
                start_tag_handlers =>
                  { 'apps/title' => \&kicks
                  },
                twig_roots =>
                  { 'apps' => \&app
                  },
                end_tag_handlers =>
                  { 'apps/logs' => \&bye
                  }
                );
    $twig -> parsefile( "doc.xml");

    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";
    }

这是doc.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 parse.pl
    ---kicks---

    ---app---
    watchset,start,00:00,alart,endcsv
    ---kicks---

    ---app---
    machinedown,select,vol_100,check,line,enddump

1 个答案:

答案 0 :(得分:9)

查看start_tag_handlersXML::Twig文档:

  

处理程序用2个参数调用:树枝和元素。该元素在该点为空,但其属性是通过。

创建的

在调用start_tag_handlers时,文本内容甚至还没有看到,因为解析了开始标记(例如<title>,而不是结束标记{ {1}})刚刚完成。

</title>不提供元素文本的原因可能是对称: - )。

您想要的可能是使用end_tag_handlers代替:

twig_handlers

输出是:

my $twig = XML::Twig->new(
    twig_handlers => {
        'apps/title' => \&kicks,
        'apps/logs' => \&bye
    },
    twig_roots => {
        'apps' => \&app
    },
);
相关问题