如何在 Perl 中使用 XML::Simple 解析多记录 XML 文件
我的 data.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>
我的 test.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章 我用文章代码进行了测试,它在我的笔记本电脑上运行得很好。
然后我在上面创建了练习代码来尝试访问多个记录。但失败了。我该如何修复它?谢谢。
My data.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>
my test.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";
Output:
Not a HASH reference at D:\learning\perl\t1.pl line 16.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
始终
使用严格;
,始终使用警告;
不要像您所做的那样引用复杂的引用。您使用 Dumper 是正确的;它应该向您显示 cd 是一个数组引用 - 您必须指定哪个 cd。Always
use strict;
, alwaysuse warnings;
Don't quote complex references like you're doing. You're right touse Dumper;
, it should have shown you thatcd
was an array ref - you have to specificity which cd.如果你执行
print Dumper($data)
,你会发现数据结构并不像你想象的那样:你需要像这样访问数据:
If you do
print Dumper($data)
, you will see that the data structure does not look like you think it does:You need to access the data like so:
除了 Evan 所说的之外,如果您不确定是否被一个或多个元素困住,ref() 可以告诉你它是什么,你可以相应地处理它:
In addition to what has been said by Evan, if you're unsure if you're stuck with one or many elements, ref() can tell you what it is, and you can handle it accordingly: