lilili07 has asked for the wisdom of the Perl Monks concerning the following question:

suppose I have a xml file: class_report.xml:
<root> <class name='music'> <record type='month' index='0'> # for the students of 1st mont +h. <string>sam1</string> <string>sam2</string> </record> <record type='month' index='1'> # for the students of 2nd mont +h. <string>mike1</string> <string>mike2</string> </record> </class> <class name='english'> <record type='week' index='2'> #for the students of 3rd week. <string>luke1</string> <string>luke2</string> </record> <record type='month' index='3'> # for the students of 3nd mont +h. <string>ben1</string> <string>ben2</string> </record> </class> </root>
How to parse the xml so that I can get a string list of class name = english, type = month and index = 3? Here is my code using twig:
use XML::Twig; #purpose: get the string of the related $class+$month+index sub parse_a_counter { my ($twig, $class) = @_; my $class_name = $class->{'att'}->{'name'}; my @report = $class->children('report [@type="month"]'); for my $report (@report){ my @string_list = $report->children_text('string'); } $class->flush; # free the memory of $counter } my $roots = { 'class[@name="english"]' => 1 }; my $handlers = { class => \&parse_a_counter }; my $twig = new XML::Twig(TwigRoots => $roots, TwigHandlers => $handlers); $twig->parsefile('class_report.xml');

20100713 Janitored by Corion: Added formatting, code tags, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: how to write this condition in XML:TWIG
by toolic (Bishop) on Jul 12, 2010 at 01:39 UTC
    Welcome to the Monastery, and please read Writeup Formatting Tips.

    If I correctly deciphered your XML, then you are probably looking for something like:

    use strict; use warnings; my $xml = <<XML; <?xml version="1.0" encoding="utf-8"?> <root> <class name="music"> <record type="month" index="0"> <string>sam1</string> <string>sam2</string> </record> <record type="month" index="1"> <string>mike1</string> <string>mike2</string> </record> </class> <class name="english"> <record type="week" index="2"> <string>luke1</string> <string>luke2</string> </record> <record type="month" index="3"> <string>ben1</string> <string>ben2</string> </record> </class> </root> XML use XML::Twig; my $t = XML::Twig->new(twig_handlers => {class => \&class}); $t->parse($xml); sub class { my ($twig, $cl) = @_; print "class name = ", $cl->att('name'), "\n"; for my $rec ($cl->children('record')) { print "type = ", $rec->att('type'); print ", index = ", $rec->att('index'), "\n"; } } __END__ class name = music type = month, index = 0 type = month, index = 1 class name = english type = week, index = 2 type = month, index = 3