软件开发网

2013 年 4 月 3 日4760

例子二:通过Xalan1.2,使用XSLT转换XML

做为第二个例子,我们使用了Xalan-Java的XSLT引擎,这个引擎来自于APACHE的XML项目,使用这个程序,我们能够使用XSL转换XML源文件。这将极大的方便我们处理文档和进行内容管理。

开始之前,我们需要将xerces.jar和xalan.jar文件放入java.class.path目录下(这两个文件包含在Xalan-Java1.2中,可以从xml.apache.org处下载)。
PHP程序如下:
函数xslt_transform()以XML和XSL文件为参数,形式可为文件名(如:foo.xml)或URL(如:http://localhost/foo.xml)。

<?php

functionxslt_transform($xml,$xsl){

//CreateaXSLTProcessorFactoryobject.XSLTProcessorfactoryisaJava
//classwhichmanufacturestheprocessorforperformingtransformations.
$XSLTProcessorFactory=newjava("org.apache.xalan.xslt.XSLTProcessorFactory");

//UsetheXSLTProcessorFactorymethodgetProcessor()tocreatea
//newXSLTProcessorobject.
$XSLTProcessor=$XSLTProcessorFactory->getProcessor();

//UseXSLTInputSourceobjectstoprovideinputtotheXSLTProcessor
//process()methodfortransformation.Createobjectsforboththe
//xmlsourceaswellastheXSLinputsource.Parameterof
//XSLTInputSourceis(inthiscase)a'systemidentifier'(URI)which
//canbeanURLorfilename.IfthesystemidentifierisanURL,it
//mustbefullyresolved.
$xmlID=newjava("org.apache.xalan.xslt.XSLTInputSource",$xml);
$stylesheetID=newjava("org.apache.xalan.xslt.XSLTInputSource",$xsl);

//CreateastringWriterobjectfortheoutput.
$stringWriter=newjava("java.io.StringWriter");

//CreateaResultTargetobjectfortheoutputwiththeXSLTResultTarget
//class.ParameterofXSLTResultTargetis(inthiscase)a'character
//stream',whichisthestringWriterobject.
$resultTarget=newjava("org.apache.xalan.xslt.XSLTResultTarget",$stringWriter);

//ProcessinputwiththeXSLTProcessors'methodprocess().This
//methodusestheXSLstylesheettotransformtheXMLinput,placing
//theresultintheresulttarget.
$XSLTProcessor->process($xmlID,$stylesheetID,$resultTarget);

//UsethestringWriters'methodtoString()to
//returnthebuffer'scurrentvalueasastringtogetthe
//transformedresult.
$result=$stringWriter->toString();
$stringWriter->close();
return($result);
}

?>

函数定义好后,我们就可以调用它了,在下面的例程中,变量$xml指向一个URL字符串,$xsl也是如此。这个例子将显示5个最新的phPBuilder.com文章标题。

<?php

$xml="http://http://www.zjjv.com///rss_feed.php?type=articles&limit=5";
$xsl="http://http://www.zjjv.com///code/xml/rss_html.xsl";
$out=xslt_transform($xml,$xsl);
echo$out;

?>

如果你在本地机上运行程序,必须确保你的函数参数指向正确的文件名。

<?php

$xml="/Web/htdocs/xml_java/rss_feed.xml";
$xsl="/web/htdocs/xml_java/rss_html.xsl";
$out=xslt_transform($xml,$xsl);
echo$out;

?>

虽然这种效果我们可以通过其它方法实现,或许那些方法更好,但这个例子能让你对PHP调用JAVA类有一个更好的了解。

0 0