XSL简明教程(4)在服务器端的实现

来源:互联网 发布:js递归遍历json树 编辑:程序博客网 时间:2024/05/17 02:05
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
四: XSL --- 在服务器端实现

1.兼容所有的浏览器

在上面一章我们介绍了可以通过JavaScript调用浏览器的XML parser(解析软件)来转换XML文档。但是这个方案依然有个问题:如果浏览器没有XML parser插件怎么办?(注:IE5内自带XML parser)

为了使我们的XML数据能被所有的浏览器正确显示,我们不得不在服务器端将XML转换成纯HTML代码,再输出给浏览器。

这也是使用XSL的另一个好处。在服务器端将一种格式转换为另一种格式也是XSL的设计目标之一。

同样,转换工作也将成为未来服务器段的主要工作。

2.一个具体实例

下面是我们上面提到的一个XML文档(cd_catalog.xml)例子的部分代码:

<?xml version="1.0" encoding="ISO8859-1" ?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
.
.
.

下面是完整的XSL文件(cd_catalog.XSL):

<?xml version='1.0'?>
<XSL:stylesheet xmlns:XSL="http://www.w3.org/TR/WD-XSL">
<XSL:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr>
<th>Title</th>
<th>Artist</th>
</tr>
<XSL:for-each select="CATALOG/CD">
<tr>
<td><XSL:value-of select="TITLE"/></td>
<td><XSL:value-of select="ARTIST"/></td>
</tr>
</XSL:for-each>
</table>
</body>
</html>
</XSL:template>
</XSL:stylesheet>

下面是在服务器端转换XML文件为HTML文件的原代码:

<%
'Load the XML
set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath("cd_catalog.xml"))
'Load the XSL
set XSL = Server.CreateObject("Microsoft.XMLDOM")
XSL.async = false
XSL.load(Server.MapPath("cd_catalog.XSL"))
Response.Write(xml.transformNode(XSL))
%>

注意:我们这里的例子采用的是ASP文件,用VBScript编写的。如果您不了解ASP或者VBScript,建议阅读有关书籍。(当然,也可以采用其他的语言编写服务器端程序)

第一段代码建立一个Microsoft Parser(XMLDOM)解析的对象,并将XML文档读入内存;第二段代码建立另外一个对象并导入XSL文档;最后一行代码将XML文档用XSL文档转换,并将结果输出到HTML文件中。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击