如何在 Perl 中使用 XML::Simple 解析多记录 XML 文件 [英] How to parse multi record XML file ues XML::Simple in Perl

查看:38
本文介绍了如何在 Perl 中使用 XML::Simple 解析多记录 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd country="UK">
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <price>10.0</price>
  </cd>
  <cd country="CHN">
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <price>9.99</price>
  </cd>
  <cd country="USA">
    <title>Hello</title>
    <artist>Say Hello</artist>
    <price>0001</price>
  </cd>
</catalog>

我的测试.pl

#!/usr/bin/perl

   # use module
   use XML::Simple;
   use Data::Dumper;

   # create object
   $xml = new XML::Simple;

   # read XML file
   $data = $xml->XMLin("data.xml");

   # access XML data
   print "$data->{cd}->{country}\n";
   print "$data->{cd}->{artist}\n";
   print "$data->{cd}->{price}\n";
   print "$data->{cd}->{title}\n";

输出:

Not a HASH reference at D:\learning\perl\t1.pl line 16.

评论:我用谷歌搜索并找到了文章(处理单个 xml 记录).http://www.go4expert.com/forums/showthread.php?t=812我使用文章代码进行了测试,它在我的笔记本电脑上运行良好.

Comment: I googled and found the article(handle single xml record). http://www.go4expert.com/forums/showthread.php?t=812 I tested with the article code, it works quite well on my laptop.

然后我在上面创建了我的练习代码来尝试访问多个记录.但失败了.我该如何解决?谢谢.

Then I created my practice code above to try to access multiple record. but failed. How can I fix it? Thank you.

推荐答案

Always use strict;, always use warnings; 不要像你这样引用复杂的引用正在做.使用 Dumper; 是正确的,它应该告诉你 cd 是一个数组引用 - 你必须明确哪个 cd.

Always use strict;, always use warnings; Don't quote complex references like you're doing. You're right to use Dumper;, it should have shown you that cd was an array ref - you have to specificity which cd.

#!/usr/bin/perl
use strict;
use warnings;

# use module
use XML::Simple;
use Data::Dumper;

# create object
my $xml = new XML::Simple;

# read XML file
my $data = $xml->XMLin("file.xml");

# access XML data
print $data->{cd}[0]{country};
print $data->{cd}[0]{artist};
print $data->{cd}[0]{price};
print $data->{cd}[0]{title};

这篇关于如何在 Perl 中使用 XML::Simple 解析多记录 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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