How to get content using XML :: Twig?

My goal is that start_tag_handler (see below) gets the contents of apps / title when it finds the apps / title tag (see XML example below).

And end_tag_handler gets the contents of apps / logs when it finds the apps / logs tag.

But instead, this code returns null and exits.

This is the Perl code for parsing (using 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"; } 

This is 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> 

This is the output in the console ###:

  C:\>perl parse.pl ---kicks--- ---app--- watchset,start,00:00,alart,endcsv ---kicks--- ---app--- machinedown,select,vol_100,check,line,enddump 
+6
xml perl xml-twig
source share
1 answer

Check out the XML::Twig documentation for start_tag_handlers :

Handlers are called with two parameters: a branch and an element. An element is empty at this point, its attributes are created though.

At the time when start_tag_handlers is start_tag_handlers , the text content is not yet visible, because the parsing of the start tag (for example, <title> , and not the end tag </title> ) has just completed.

The reason end_tag_handlers does not contain element text is probably for symmetry end_tag_handlers .

You can use twig_handlers :

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

Exit:

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

All Articles