2005-12-11

快速开始Perl XML:接口篇

来源: 本站收集整理 作者:佚名 评论 0 条
 

任务二:创建一个XML文档

为了示范每一模块是如何从其他数据源中创建新的XML文档,我们将写一个小脚本将一个简单的Perl hash转换为一个简单的XHTML文档。hash里包含一些指向很cool的特定相关骆驼的网页的URLs。

Hash 如下:

my 蕀elid_links = (

    one   => { url         => '

    http://www.online.discovery.com/news/picture/may99/photo20.html',

               description => 'Bactrian Camel in front of Great ' .

                              'Pyramids in Giza, Egypt.'},

    two   => { url         => 'http://www.fotos-online.de/english/m/09/9532.htm',

               description => 'Dromedary Camel illustrates the ' . 

                              'importance of accessorizing.'},

    three => { url         => 'http://www.eskimo.com/~wallama/funny.htm',

               description => 'Charlie - biography of a narcissistic llama.'},

    four  => { url         => 'http://arrow.colorado.edu/travels/other/turkey.html',

               description => 'A visual metaphor for the perl5-porters ' .

                              'list?'},

    five  => { url         => 'http://www.galaonline.org/pics.htm',

               description => 'Many cool alpacas.'},

    six   => { url         => 'http://www.thpf.de/suedamerikareise/galerie/vicunas.htm',

               description => 'Wild Vicunas in a scenic landscape.'}

);

而我们所期望从hash中创建的文档例子为:


<?xml version="1.0">

<html>

  <body>

    <a href="http://www.eskimo.com/~wallama/funny.htm">Charlie - 

      biography of a narcissistic llama.</a>

    <a href="http://www.online.discovery.com/news/picture/may99/photo20.html">Bactrian

      Camel in front of Great Pyramids in Giza, Egypt.</a>

    <a href="http://www.fotos-online.de/english/m/09/9532.htm">Dromedary

      Camel illustrates the importance of accessorizing.</a>

    <a href="http://www.galaonline.org/pics.htm">Many cool alpacas.</a>

    <a href="http://arrow.colorado.edu/travels/other/turkey.html">A visual 

      metaphor for the perl5-porters list?</a>

    <a href="http://www.thpf.de/suedamerikareise/galerie/vicunas.htm">Wild

      Vicunas in a scenic landscape.</a>

  </body>

</html>

良好缩进的XML结果文件(如上面所显示的)对于阅读很重要,但这种良好的空格处理不是我们案例所要求的。我们所关心的是结果文档是结构良好的/well-formed和它正确地表现了hash里的数据。

任务定义完毕,接下来该是代码例子的时候了。

XML Perl专用接口例子

XML::Simple

最初创建用来简化读写XML格式配置文件的XML::Simple, 在转换XML文档和Perl数据结构之间没有另外的抽象接口。所有的元素和属性都可以通过嵌套的引用直接读取。

Reading

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}->final . "\n";

}




共4页: 上一页 [1] 2 [3] [4] 下一页
(本文仅表明作者个人观点,不代表本站及其管理员立场.) 推荐 收藏 投稿 打印 返回 关闭
上一篇:hao123站长李兴平的成功史  
下一篇:当客网:我们更注重用户体验
    评论加载中…
 推荐文章
     

网站首页  -  网站地图 -   站长论坛  -  网站投稿  -    -  网站管理
Copyright © 2008 芜湖站长站 All Rights Reserved 皖ICP备07500611号