I have an XML and I want to print all his nodes and I want to access the movie nodes fields.
I can access Name and City, but I can`t access Movie fields.
<OnlineCinema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Cinema.xsd">
<Cinema>
<City>Cluj</City>
<Name>Cinema2</Name>
<MovieName>ScaryMovie</MovieName>
<Movie>
<Name>ScaryMovie</Name>
<Genre>comedie</Genre>
<Director>lala</Director>
<Writer>asdf</Writer>
<Cast>asdvvb</Cast>
<Year>2010</Year>
<Trailer>http://www.youtube.com/embed/RMDZ8M47j0I</Trailer>
<NRLoc>400</NRLoc>
</Movie>
</Cinema>
Code:
use XML::Simple;
use Data::Dumper;
$xml = new XML::Simple (KeyAttr=>[]);
$data = $xml->XMLin("OnlineCinema.xml");
print "Content-type: text/html \n\n";
foreach $e (@{$data->{Cinema}}) {
print "City: ", $e->{City}, "</br>\n";
print "Name: ", $e->{Name}, "</br>\n";
print "</br></br>\n";
}
XML::Simple is the hardest XML parser to use. I use XML::LibXML.
(I assumed a Cinema can have more than one Movie, but given the presence of MovieName in Cinema, that might not be the case. It'll still work if it's not the case, but you might want to eliminate the inner
for
loop.)Try that:
Basically, you are asking to go through the array of
Cinema
entries in your xml, but in this instance, since there's only one of them, it is built as a single scalar value. TheForceArray
option tells the libray to consider that entry as a one element array, or more precisely, for any xml fed to the script, theCinema
tag(s) will always be made as an array of tags, whether there's one or more of them. That option may take:1
to force it to all tags,0
to not use it (which is the default)Oh, and add a closing
OnlineCinema
tag at the end of your xml to have it parsed correctly.