sherab has asked for the wisdom of the Perl Monks concerning the following question:
Hi folks, I am having an issue parsing XML using Perl's XML::Simple. The XML file I am parsing is below....
(It's called cars.xml)
Hyundai
20000
Jeep
10000
Not an ARRAY reference at ./node_test2.pl line 15
What I like about the above is that referencing model and mileage info is easy using the foreach routine above. What I need to do is to equally access the attributes of "id" and "content" in an equally simple way. Of course I may just need to use something else besides XML::Simple too but I thought I'd see if the monks had any ideas.
Using Data::Dumper on this yields....<?xml version="1.0"?> <root> <unsold> <car> <model>Hyundai</model> <mileage>20000</mileage> </car> <car> <model>Jeep</model> <mileage>10000</mileage> </car> </unsold> <footnotes> <footnote id = "F1">F1 text</footnote> <footnote id = "F2">F2 text</footnote> </footnotes> </root>
The script I am using is below....$VAR1 = { 'unsold' => { 'car' => [ { 'model' => 'Hyundai', 'mileage' => '20000' }, { 'model' => 'Jeep', 'mileage' => '10000' } ] }, 'footnotes' => { 'footnote' => { 'F2' => { 'content' => 'F2 text' }, 'F1' => { 'content' => 'F1 text' } } } };
Running code yields this....#!/usr/bin/perl use XML::Simple; use Data::Dumper; $xml = new XML::Simple; $data = $xml->XMLin("cars.xml", forcearray => ['footnote', 'car', 'id' +]) or die "Sorry no can do:$!"; #$data = $xml->XMLin("cars.xml") or die "Sorry no can do:$!"; print Dumper($data); exit; foreach $e (@{$data->{unsold}{car}}) { print "$e->{model}"; print "$e->{mileage}"; } foreach $e (@{$data->{footnotes}}) { print "$e->{footnote}{content}\n"; }
Hyundai
20000
Jeep
10000
Not an ARRAY reference at ./node_test2.pl line 15
What I like about the above is that referencing model and mileage info is easy using the foreach routine above. What I need to do is to equally access the attributes of "id" and "content" in an equally simple way. Of course I may just need to use something else besides XML::Simple too but I thought I'd see if the monks had any ideas.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Accessing attributes in XML::Simple
by ikegami (Patriarch) on Dec 31, 2009 at 20:32 UTC | |
by Jenda (Abbot) on Jan 02, 2010 at 12:48 UTC | |
by ikegami (Patriarch) on Jan 02, 2010 at 16:42 UTC | |
by sherab (Scribe) on Jan 05, 2010 at 03:28 UTC | |
by ikegami (Patriarch) on Jan 05, 2010 at 03:34 UTC | |
by sherab (Scribe) on Jan 05, 2010 at 03:36 UTC | |
Re: Accessing attributes in XML::Simple
by toolic (Bishop) on Dec 31, 2009 at 20:09 UTC | |
Re: Accessing attributes in XML::Simple
by gube (Parson) on Dec 31, 2009 at 20:33 UTC | |
by ikegami (Patriarch) on Dec 31, 2009 at 20:39 UTC | |
by gube (Parson) on Dec 31, 2009 at 22:55 UTC |
Back to
Seekers of Perl Wisdom