使用 XMLRabbit 使用 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 "Purchase price: ". $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>