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

I looked in the archives and found a couple of posts that were similar to what I was looking for, but not quite what I needed. I'd love if someone could explain why this works for one, but not the other - First things - Data:
'record' => [ { 'xmlns' => 'http://www.loc.gov/MARC21/slim', 'xmlns:xsi' =>something', 'xsi:schemaLocation' => somehtml', 'datafield' => [ { 'ind1' => ' ', 'ind2' => ' ', 'subfield' => [ { 'content' => '0047-3936', 'code' => 'a' } ], tag' => '022' }, { 'ind1' => '1', 'ind2' => '0', 'subfield' => [ { 'content' => 'more content here', 'code' => 'a' } ], 'tag' => '245' } ] }, repeat this structure entry x10
So, this is one entry in a list of 10 thats produced - now, if I use this code:
my $xml = new XML::Simple (ForceArray => 1, KeyAttr=>[]); $data = $xml->XMLin($dirtyxml); foreach $record(@{$data->{present_response}->{record}}) { $gooddata=$record->{xmlns}; push(@title, $gooddata); } foreach (@title) { $list = $list."<p>".$_."</p>"; } my $output = "<p>".$list."</p>"; return($output);
I can easily pull and display the values of {xmlns} for each entry, but attempting to pull {datafield}->{subfield}->{content} (notice there can be 2 or more per entry), using the same method, I get nothing - eg.
foreach $subfield (@{$data->{present_response}->{record}->{datafield}- +>{subfield}}) { $gooddata=$subfield->{content}; push(@title, $gooddata); }
any words of wisdom? Thanks!

Replies are listed 'Best First'.
Re: Parsing with XML::Simple - repeated elements will not parse correctly
by ikegami (Patriarch) on Nov 27, 2007 at 17:21 UTC
    There can be more than one datafield and subfield, so you have to identify which one.
    $data->{datafield}[$i]{subfield}[$j]{content}
    my $datafields = $data->{datafield}; foreach my $datafield (@$datafields) { my $subfields = $datafield->{subfield}; foreach my $subfield (@$subfields) { my ($content, $code) = @{$subfield}{qw( content code )}; ... } }