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

tkn*_*knv 6 xml perl xml-twig

我的目标是start_tag_handler(见下文)在找到/ tag 时获取apps/ titlecontent (请参阅下面的示例XML).appstitle

end_tag_handler在找到/ tag 时获取apps/ logscontent .appslogs

但相反,此代码返回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";
    }
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

这是控制台###中的输出:

    C:\>perl parse.pl
    ---kicks---

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

    ---app---
    machinedown,select,vol_100,check,line,enddump
Run Code Online (Sandbox Code Playgroud)

Ins*_*lah 9

查看以下XML::Twig文档start_tag_handlers:

处理程序用2个参数调用:树枝和元素.此时元素为空,但是会创建其属性.

start_tag_handlers调用时,文本内容甚至还没有被看到,因为开始标记的解析(例如<title>,不是结束标记</title>)刚刚完成.

end_tag_handlers不提供元素文本的原因可能是对称:-).

您想要的可能是使用twig_handlers:

my $twig = XML::Twig->new(
    twig_handlers => {
        'apps/title' => \&kicks,
        'apps/logs' => \&bye
    },
    twig_roots => {
        'apps' => \&app
    },
);
Run Code Online (Sandbox Code Playgroud)

输出是:

---kicks--- 
watch 
bye 
csv 
---app--- 
watchset,start,00:00,alart,endcsv
---kicks--- 
machine 
bye 
dump 
---app--- 
machinedown,select,vol_100,check,line,enddump
Run Code Online (Sandbox Code Playgroud)