DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
Perl 與 XML 快速上手(一):Perl 專用介面篇
編輯:XML詳解     

前言

在 Perl-XML 郵件論壇裡,最常被提出的一個問題是:有沒有一份能讓新手快速掌握 CPAN 上大量 XML 模組的入門導覽?接下來幾期專欄,我會針對這個需求分篇說明。

CPAN 上的 XML 模組大致可以分成三類:第一類是為 XML 資料提供獨特介面的模組,核心工作是在 XML 文件與 Perl 資料結構之間轉換;第二類是實作某個標準 XML API 的模組;第三類則是針對特定 XML 任務做簡化的特殊用途模組。本期先談第一類,也就是 Perl 專用介面。

一份小小的聲明

這篇文章不是效能評測,我也不打算暗示某個模組比另一個更優秀。要為專案挑選合適的 XML 模組,取決於專案本身的性質以及你累積的經驗——不同的介面適合不同的任務,也適合不同的人。我唯一想做的事,是用兩個簡單的任務,示範如何用不同模組得到同一個結果。

兩個任務

XML 的用途千變萬化,但絕大多數工作可以歸為兩類:從既有的 XML 文件裡取出資料,或利用其他來源的資料建立一份新的 XML 文件。因此,本文的範例也由兩部分組成:「從 XML 檔案中擷取特定資料」以及「把 Perl 資料結構轉成特定的 XML 格式」。

任務一:擷取資料

先看一段 XML 片段:

<?xml version="1.0"?>
<camelids>
  <species name="Camelus dromedarius">
    <common-name>Dromedary, or Arabian Camel</common-name>
    <physical-characteristics>
      <mass>300 to 690 kg.</mass>
      <appearance>長而彎曲的頸部、窄深的胸腔,以及單一駝峰……</appearance>
    </physical-characteristics>
    <natural-history>
      <food-habits>單峰駱駝是草食性動物……</food-habits>
      <reproduction>壽命約為 40 至 50 年……</reproduction>
      <habitat>偏好長旱季、短雨季的沙漠環境……</habitat>
    </natural-history>
    <conservation status="no special status">
      <detail>由於已被馴化,單峰駱駝沒有特別的保育等級。</detail>
    </conservation>
  </species>
  ...
</camelids>

假設完整文件(可從本月範例程式碼取得)涵蓋整個駱駝科的所有成員,而不只是單峰駱駝。為了示範每個模組如何從中取出資料子集,我們會寫一個很短的腳本,處理 camelids.xml,並在 STDOUT 上輸出每一種駱駝的常見名稱、學名(放在括號中)以及目前的保育狀態。處理完整份文件後,輸出結果如下:

Bactrian Camel (Camelus bactrianus) endangered
Dromedary, or Arabian Camel (Camelus dromedarius) no special status
Llama (Lama glama) no special status
Guanaco (Lama guanicoe) special concern
Vicuna (Vicugna vicugna) endangered

任務二:建立一份 XML 文件

為了示範各模組如何從其他資料來源產生新的 XML 文件,我們寫一個小腳本,把簡單的 Perl hash 轉換成簡短的 XHTML 文件。這個 hash 收錄了幾個關於駱駝的網站連結。

my %camelid_links = (
    one   => { url => 'https://www.online.discovery.com/news/picture/may99/photo20.html',
                description => 'Bactrian Camel in front of Great Pyramids in Giza, Egypt.' },
    two   => { url => 'https://www.fotos-online.de/english/m/09/9532.htm',
                description => 'Dromedary Camel illustrates the importance of Accessorizing.' },
    three => { url => 'https://www.eskimo.com/~wallama/funny.htm',
                description => 'Charlie - biography of a narcissistic llama.' },
    four  => { url => 'https://arrow.colorado.edu/travels/other/turkey.html',
                description => 'A visual metaphor for the perl5-porters list?' },
    five  => { url => 'https://www.galaonline.org/pics.htm',
                description => 'Many cool alpacas.' },
    six   => { url => 'https://www.thpf.de/suedamerikareise/galerie/vicunas.htm',
                description => 'Wild Vicunas in a scenic landscape.' },
);

期望產出的文件如下:

<?xml version="1.0"?>
<html>
  <body>
    <a href="https://www.eskimo.com/~wallama/funny.htm">Charlie - biography of a narcissistic llama.</a>
    <a href="https://www.online.discovery.com/news/picture/may99/photo20.html">Bactrian Camel in front of Great Pyramids in Giza, Egypt.</a>
    ...
  </body>
</html>

縮排漂亮的 XML 當然比較好讀,但這不是本案例的重點。我們真正在意的是:結果文件必須是 well-formed,而且正確反映了 hash 裡的資料。

Perl 專用介面的實作範例

XML::Simple

XML::Simple 最初是為了簡化 XML 設定檔的讀寫而生,它在 XML 文件與 Perl 資料結構之間沒有額外的抽象層,所有元素與屬性都能透過嵌套參照直接存取。

讀取

use XML::Simple;

my $file = 'files/camelids.xml';
my $xs1  = XML::Simple->new();
my $doc  = $xs1->XMLin($file);

foreach my $key (keys %{$doc->{species}}) {
    print $doc->{species}{$key}{'common-name'} . " ($key) ";
    print $doc->{species}{$key}{conservation}{status} . "\n";
}

寫入

use XML::Simple;
require "files/camelid_links.pl";

my %camelid_links = get_camelid_data();
my $xsimple = XML::Simple->new();
print $xsimple->XMLout(\%camelid_links,
    noattr  => 1,
    XMLdecl => '<?xml version="1.0"?>');

「資料轉文件」這個任務暴露了 XML::Simple 的一個弱點:它無法讓你決定 hash 裡哪個鍵該輸出成元素、哪個鍵該輸出成屬性。上面的輸出雖然接近需求,卻還不夠。如果你偏好直接以 Perl 資料結構操作 XML 內容,同時又需要在輸出上更細緻的控制,把 XML::Simple 與 XML::Writer 搭配使用會很合適。

use XML::Writer;
require "files/camelid_links.pl";

my %camelid_links = get_camelid_data();
my $writer = XML::Writer->new();
$writer->xmlDecl();
$writer->startTag('html');
$writer->startTag('body');
foreach my $item (keys %camelid_links) {
    $writer->startTag('a', 'href' => $camelid_links{$item}{url});
    $writer->characters($camelid_links{$item}{description});
    $writer->endTag('a');
}
$writer->endTag('body');
$writer->endTag('html');
$writer->end();

XML::SimpleObject

XML::SimpleObject 以類似 DOM 的 Accessor 風格,為 XML 資料提供物件導向介面。

讀取

use XML::Parser;
use XML::SimpleObject;

my $file   = 'files/camelids.xml';
my $parser = XML::Parser->new(ErrorContext => 2, Style => 'Tree');
my $xso    = XML::SimpleObject->new($parser->parsefile($file));

foreach my $species ($xso->child('camelids')->children('species')) {
    print $species->child('common-name')->{VALUE};
    print ' (' . $species->attribute('name') . ') ';
    print $species->child('conservation')->attribute('status') . "\n";
}

寫入

XML::SimpleObject 本身不具備產生 XML 文件的能力。不過與 XML::Simple 一樣,搭配 XML::Writer 就能輕鬆完成任務。

XML::TreeBuilder

這個套件由兩個模組組成:XML::Element 負責建立與取得 XML 元素節點的內容,XML::TreeBuilder 則作為工廠,簡化從既有 XML 檔案建立文件樹的工作。如果你已經熟悉 HTML::Element 與 HTML::Tree,那麼除了 XML 特有的方法之外,其餘用法幾乎一模一樣。

讀取

use XML::TreeBuilder;

my $file = 'files/camelids.xml';
my $tree = XML::TreeBuilder->new();
$tree->parse_file($file);

foreach my $species ($tree->find_by_tag_name('species')) {
    print $species->find_by_tag_name('common-name')->as_text;
    print ' (' . $species->attr_get_i('name') . ') ';
    print $species->find_by_tag_name('conservation')->attr_get_i('status') . "\n";
}

寫入

use XML::Element;
require "files/camelid_links.pl";

my %camelid_links = get_camelid_data();

my $root   = XML::Element->new('html');
my $body   = XML::Element->new('body');
my $xml_pi = XML::Element->new('~pi', text => 'xml version="1.0"');
$root->push_content($body);

foreach my $item (keys %camelid_links) {
    my $link = XML::Element->new('a', 'href' => $camelid_links{$item}{url});
    $link->push_content($camelid_links{$item}{description});
    $body->push_content($link);
}

print $xml_pi->as_XML;
print $root->as_XML;

XML::Twig

XML::Twig 與其他純 Perl 介面不同,它在標準 XML API 之外,還提供了許多富有創意的 Perlish 特色。想深入了解,可以參考 XML.com 上的專文。

讀取

use XML::Twig;

my $file = 'files/camelids.xml';
my $twig = XML::Twig->new();
$twig->parsefile($file);
my $root = $twig->root;

foreach my $species ($root->children('species')) {
    print $species->first_child_text('common-name');
    print ' (' . $species->att('name') . ') ';
    print $species->first_child('conservation')->att('status') . "\n";
}

寫入

use XML::Twig;
require "files/camelid_links.pl";

my %camelid_links = get_camelid_data();

my $root = XML::Twig::Elt->new('html');
my $body = XML::Twig::Elt->new('body');
$body->paste($root);

foreach my $item (keys %camelid_links) {
    my $link = XML::Twig::Elt->new('a');
    $link->set_att('href', $camelid_links{$item}{url});
    $link->set_text($camelid_links{$item}{description});
    $link->paste('last_child', $body);
}

print qq|<?xml version="1.0"?>|;
$root->print;

以上範例展示了這些常見 Perl XML 模組的基本用法,希望足以讓你感受每個模組的 coding 風格。下期我們將談「實作標準 XML API 的模組」,特別是 XML::DOM、XML::XPath,以及數量可觀的 SAX 與類 SAX 模組。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved