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

HI, I have this xml
<blocks_conduit_model_service_course generator="zend" version="1.0"> <get_course_grades> <users> <id_8004><user><id>8004</id><fullname>Päivi Timonen</fullname><usernam +e>timopa01</username><idnumber/></user></id_8004> <id_601><user><id>601</id><fullname>Pekka Harjula</fullname><username> +harjpe01</username><idnumber/></user></id_601> <id_5><user><id>5</id><fullname>Hanna Laitinen</fullname><username>lai +tha02</username><idnumber/></user></id_5> </users> </blocks_conduit_model_service_course> I'm using XML::Simple print "$response_xml->{get_course_grades}->{users}->{id_8004}->{user}- +>{username}" ;
I need to get the username from each element. How can I loop thru all the elements? id_ can be what ever and is in no order.

Replies are listed 'Best First'.
Re: Parsing xml
by choroba (Cardinal) on Feb 19, 2016 at 11:43 UTC
    Your XML is not well formed - the get_course_grades tag is not closed.

    Don't use XML::Simple. Its documentation itself tells you you shouldn't.

    You can use XML::LibXML instead.

    #!/usr/bin/perl use warnings; use strict; use XML::LibXML; my $xml = 'XML::LibXML'->load_xml(location => shift); for my $username ($xml->findnodes('//username')) { print $username->textContent, "\n"; }

    I usually use XML::XSH2, which is a wrapper around XML::LibXML. It simplifies the above code to

    open file.xml ; for //username echo (.) ;

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      HI, Thanks I used this and it worked fine.
      my $xml = 'XML::LibXML'->load_xml(string => $response_xml); for my $username ($xml->findnodes('//username')) { print $username->textContent, "\n"; }
      Yes the xml was badly formed I copied a long string and just pasted a few rows as an example. Thanks for your help.
Re: Parsing xml
by Discipulus (Canon) on Feb 19, 2016 at 11:49 UTC
Re: Parsing xml
by kcott (Archbishop) on Feb 19, 2016 at 12:12 UTC