Perl使用XML :: Rabbit消费XML
示例
有了XML::Rabbit它可以轻松地使用XML文件。您可以使用XPath语法以声明方式定义XML中要查找的内容,XML::Rabbit并将根据给定的定义返回对象。
定义:
package Bookstore; use XML::Rabbit::Root; has_xpath_object_list books => './book' => 'Bookstore::Book';finalize_class(); package Bookstore::Book; use XML::Rabbit; has_xpath_value bookid => './@id'; has_xpath_value author => './author'; has_xpath_value title => './title'; has_xpath_value genre => './genre'; has_xpath_value price => './price'; has_xpath_value publish_date => './publish_date'; has_xpath_value description => './description'; has_xpath_object purchase_data => './purchase_data' => 'Bookstore::Purchase';finalize_class(); package Bookstore::Purchase; use XML::Rabbit; has_xpath_value price => './price'; has_xpath_value date => './date';finalize_class();
XML消耗:
use strict;
use warnings;
use utf8;
package Library;
use feature qw(say);
use Carp;
use autodie;
say "Showing data information";
my $bookstore = Bookstore->new( file => './sample.xml' );
foreach my $book( @{$bookstore->books} ) {
say "ID: " . $book->bookid;
say "Title: " . $book->title;
say "Author: " . $book->author, "\n";
}笔记:
请注意以下几点:
头等舱必须XML::Rabbit::Root。它将把您放在XML文档的主要标签内。就我们而言,它将把我们放在里面<catalog>
嵌套类是可选的。这些类需要通过try/catch(或eval/$@check)块进行访问。可选字段将简单地返回null。例如,对于purchase_data循环将是:
foreach my $book( @{$bookstore->books} ) {
say "ID: " . $book->bookid;
say "Title: " . $book->title;
say "Author: " . $book->author;
try {
say "购买价格: ". $book->purchase_data->price, "\n";
} catch {
say "No purchase price available\n";
}
}sample.xml
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
<purchase_data>
<date>2001-12-21</date>
<price>20</price>
</purchase_data>
</book>
</catalog>