當(dāng)通過(guò)HTTP發(fā)送XML數(shù)據(jù)時(shí),就有必要使用JSP來(lái)處理傳入和流出的XML文檔了,比如RSS文檔。作為一個(gè)XML文檔,它僅僅只是一堆文本而已,使用JSP創(chuàng)建XML文檔并不比創(chuàng)建一個(gè)HTML文檔難。
使用JSP發(fā)送XML內(nèi)容就和發(fā)送HTML內(nèi)容一樣。唯一的不同就是您需要把頁(yè)面的context屬性設(shè)置為text/xml。要設(shè)置context屬性,使用<%@page % >命令,就像這樣:
<%@ page contentType="text/xml" %>
接下來(lái)這個(gè)實(shí)例向?yàn)g覽器發(fā)送XML內(nèi)容:
<%@ page contentType="text/xml" %> <books> <book> <name>Padam History</name> <author>ZARA</author> <price>100</price> </book> </books>
使用不同的瀏覽器來(lái)訪問(wèn)這個(gè)實(shí)例,看看這個(gè)實(shí)例所呈現(xiàn)的文檔樹。
在使用JSP處理XML之前,您需要將與XML 和XPath相關(guān)的兩個(gè)庫(kù)文件放在<Tomcat Installation Directory>\lib目錄下:
XercesImpl.jar:在這下載http://www.apache.org/dist/xerces/j/
xalan.jar:在這下載http://archive.apache.org/dist/xml/xalan-j/
books.xml文件:
<books> <book> <name>Padam History</name> <author>ZARA</author> <price>100</price> </book> <book> <name>Great Mistry</name> <author>NUHA</author> <price>2000</price> </book> </books>
main.jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:parse Tags</title>
</head>
<body>
<h2>Books Info:</h2>
<c:import var="bookInfo" url="http://localhost:8080/books.xml"/>
<x:parse xml="${bookInfo}" var="output"/>
<b>The title of the first book is</b>:
<x:out select="$output/books/book[1]/name" />
<br>
<b>The price of the second book</b>:
<x:out select="$output/books/book[2]/price" />
</body>
</html>訪問(wèn)http://localhost:8080/main.jsp,運(yùn)行結(jié)果如下:
BOOKS INFO: The title of the first book is:Padam History The price of the second book: 2000
這個(gè)是XSLT樣式表style.xsl文件:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl= "http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="books"> <table border="1" width="100%"> <xsl:for-each select="book"> <tr> <td> <i><xsl:value-of select="name"/></i> </td> <td> <xsl:value-of select="author"/> </td> <td> <xsl:value-of select="price"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>
這個(gè)是main.jsp文件:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:transform Tags</title>
</head>
<body>
<h2>Books Info:</h2>
<c:set var="xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
<c:import url="http://localhost:8080/style.xsl" var="xslt"/>
<x:transform xml="${xmltext}" xslt="${xslt}"/>
</body>
</html>運(yùn)行結(jié)果如下:

更多關(guān)于使用JSTL處理XML的內(nèi)容請(qǐng)查閱JSP標(biāo)準(zhǔn)標(biāo)簽庫(kù)。