In the event that mirod has not managed to convert you to XML::Twig :-) then here's one code snippet to do what (I think) you want:

#!/usr/bin/perl use strict; use warnings; use XML::Simple; my $file = './Test.xml'; my $head = $ARGV[0] || 'Unknown'; my $map = XMLin($file, forcearray => ['header', 'act'], keyattr => { h +eader => 'name'}); my $header = $map->{header}->{$head}; if($header) { foreach my $act ( @{$header->{act}} ) { print "act: $act\n"; } } else { print "No match for '$head'\n"; }

Alternatively, you could iterate through the <header> items by using the keyattr option to turn off array folding:

my $map = XMLin($file, forcearray => ['header', 'act'], keyattr => {}) +; my $headers = $map->{header}; foreach my $header (@$headers) { if($header->{name} eq $head) { foreach my $act ( @{$header->{act}} ) { print "act: $act\n"; } } }

By the way, your original code included this logic:

unless ($config = $xs1->XMLin($file, forcearray => 1)) { print "Could NOT read $file IN:$!\n"; exit(); }

That won't actually work, since if XML::Simple can't parse the XML it will call 'die' rather than returning a false value. If you want to trap errors, you'd need to wrap the call to XMLin() in an eval block and check $@ afterwards.


In reply to Re: XML::Simple parsing by grantm
in thread XML::Simple parsing by AcidHawk

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.