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

前端之家收集整理的这篇文章主要介绍了如何使用XML :: Twig获取内容?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是start_tag_handler(见下文)在找到应用程序/标题标签获取应用程序/标题内容(请参阅下面的示例 XML).


end_tag_handler在找到apps / logs标记获取应用程序/日志内容.

但相反,此代码返回null并退出.

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

  1. #!/usr/local/bin/perl -w
  2.  
  3. use XML::Twig;
  4. my $twig = XML::Twig->new(
  5. start_tag_handlers =>
  6. { 'apps/title' => \&kicks
  7. },twig_roots =>
  8. { 'apps' => \&app
  9. },end_tag_handlers =>
  10. { 'apps/logs' => \&bye
  11. }
  12. );
  13. $twig -> parsefile( "doc.xml");
  14.  
  15. sub kicks {
  16. my ($twig,$elt) = @_;
  17. print "---kicks--- \n";
  18. print $elt -> text;
  19. print " \n";
  20. }
  21.  
  22. sub app {
  23. my ($twig,$apps) = @_;
  24. print "---app--- \n";
  25. print $apps -> text;
  26. print " \n";
  27. }
  28.  
  29.  
  30. sub bye {
  31. my ($twig,$elt) = @_;
  32. print "bye \n";
  33. print $elt->text;
  34. print " \n";
  35. }

这是doc.xml ###:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <auto>
  3. <apps>
  4. <title>watch</title>
  5. <commands>set,start,00:00,alart,end</commands>
  6. <logs>csv</logs>
  7. </apps>
  8. <apps>
  9. <title>machine</title>
  10. <commands>down,select,vol_100,check,line,end</commands>
  11. <logs>dump</logs>
  12. </apps>
  13. </auto>

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

  1. C:\>perl parse.pl
  2. ---kicks---
  3.  
  4. ---app---
  5. watchset,endcsv
  6. ---kicks---
  7.  
  8. ---app---
  9. machinedown,enddump
查看 start_tag_handlers的XML :: Twig文档:

The handlers are called with 2 params: the twig and the element. The element is empty at that point,its attributes are created though.

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

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

您想要的可能是使用twig_handlers:

  1. my $twig = XML::Twig->new(
  2. twig_handlers => {
  3. 'apps/title' => \&kicks,'apps/logs' => \&bye
  4. },twig_roots => {
  5. 'apps' => \&app
  6. },);

输出是:

  1. ---kicks---
  2. watch
  3. bye
  4. csv
  5. ---app---
  6. watchset,endcsv
  7. ---kicks---
  8. machine
  9. bye
  10. dump
  11. ---app---
  12. machinedown,enddump

猜你在找的XML相关文章