用Perl和XML轻松开发多种界面的Web服务

开发者在线 Builder.com.cn 更新时间:2007-11-17作者:刘彦青编译 来源:yesky

为了简明起见,我们将使被比较文档尽量简单。第一个文档的名字为doc1.xml:









<?xml version="1.0"?>
<root>
<el1 el1attr="good"/>
<el2 el2attr="good">Some Text</el2>
<el3/>
</root>

  第二个XML文档的名字为:doc2.xml :


<?xml version="1.0"?>
<root>
<el1 el1attr="bad"/>
<el2 bogus="true"/>
<el4>Rogue</el4>
</root>

  从浏览器进行访问

  对/cgi-bin/semdiff.cgi的请求将提示用户上传二个文档:


        图1


  在对文件进行比较后,结果如下:


        图2


  从SOAP客户端访问

  SOAP::Lite既有服务器也有客户端实现。在这里我们将使用它创建一个连接我们的应用程序的SOAP界面的客户端应用程序。为了节约篇幅,我们将跳过与变量处理、打开和读取要比较的XML文档相关的客户端脚本,而重点讨论与SOAP相关的部分:


#!/usr/bin/perl -w
use strict;
use SOAP::Lite;
...
my $soap = SOAP::Lite
-> uri('http://my.host.tld/WebSemDiff')
-> proxy('http://my.host.tld/cgi-bin/semdiff.cgi')
-> on_fault( &fatal_error );

my $result = $soap->compare( $file1, $file2 )->result;

print "Comparing $f1 and $f2...n";

if ( defined $result and scalar( @ ) == 0 ) {
print "Files are semantically identicaln";
exit;
}

foreach my $diff ( @ ) {
print $diff-> . ' ' .
$diff-> . ' - ' .
$diff-> . ' ' .
$diff-> .
"n";

}

 

  将我们的二个XML文档的路径传递给该脚本代码会产生下面的结果:


Comparing docs/doc1.xml and docs/doc2.xml...
/root[1]/el1[1] 3 - 3 Attribute 'el1attr' has different value in element 'el1'.
/root[1]/el2[1] 4 - 4 Character differences in element 'el2'.
/root[1]/el2[1] 4 - 4 Attribute 'el2attr' missing from element 'el2'.
/root[1]/el2[1] 4 - 4 Rogue attribute 'bogus' in element 'el2'.
/root[1] 5 - 5 Child element 'el3' missing from element '/root[1]'.
/root[1] 5 - 5 Rogue element 'el4' in element '/root[1]'.

  另外,我们可以使用SOAP::Lite的自动调度机制来提高代码的可读性:


use SOAP::Lite +autodispatch =>
uri => 'http://my.host.tld/WebSemDiff',
proxy =>'http://my.host.tld/cgi-bin/semdiff.cgi',
on_fault => &fatal_error ;

my $result = SOAP->compare( $file1, $file2 );

print "Comparing $f1 and $f2...n";

# etc ..
 

用户评论

  • 用户名
  • 评论内容