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

6
我的目标是让下面的start_tag_handler在找到apps/title标签时获取其内容(见下面的示例XML)。
end_tag_handler找到apps/logs标签时,它将获取其内容。
但是,实际上这段代码返回null并退出。
以下是用Perl解析XML(使用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个回答

10

查看XML::Twig文档中的start_tag_handlers

处理程序使用2个参数调用:twig和元素。此时的element为空,但其属性已创建。

在调用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
    },
);

输出结果为:

---kicks--- 
watch 
bye 
csv 
---app--- 
watchset,start,00:00,alart,endcsv
---kicks--- 
machine 
bye 
dump 
---app--- 
machinedown,select,vol_100,check,line,enddump

非常感谢,我会尝试您的想法,然后再发表更多评论。我误解了XML::Twig文档,我以为start_tag_handlers在那个时候就知道了... - tknv
twig_handlers是调用处理程序的常规方式,只有在使用twig_handlers不可能时(例如元素可能太大)才应该使用start_tag_handlers。如文档中所述,应尽量少使用end_tag_handlers。 - mirod
它可以工作!哇,作者。我会仔细阅读。-> 给mirod。非常感谢,有点惊讶于作者的评论。 - tknv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接