在Perl中解析复杂的XML [英] Parsing complex XML in Perl

查看:106
本文介绍了在Perl中解析复杂的XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML,我想打印他的所有节点,并且要访问电影节点字段.

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>

代码:

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是最难使用的XML解析器.我使用XML :: LibXML.

XML::Simple is the hardest XML parser to use. I use XML::LibXML.

use strict;
use warnings;

use XML::LibXML qw( );

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file('OnlineCinema.xml');

for my $cinema ($doc->findnodes('/OnlineCinema/Cinema')) {
   my $cinema_name = $cinema->find('Name');
   my $cinema_city = $cinema->find('City');

   for my $movie ($cinema->findnodes('Movie')) {
      my $movie_name  = $movie->find('Name');
      my $movie_genre = $movie->find('Genre');

      print("$movie_name ($movie_genre) is playing at the $cinema_name in $cinema_city\n");
   }
}

(我假设电影可以有多个 Movie ,但是考虑到 Cinema 中存在 MovieName >,情况可能并非如此.如果不是这样,它仍然可以工作,但是您可能要消除内部的for循环.)

(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.)

这篇关于在Perl中解析复杂的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆