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


In reply to how to write this condition in XML:TWIG by lilili07

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.