當通過HTTP發送XML數據時,就有必要使用JSP來處理傳入和流出的XML文檔了,比如RSS文檔。作為一個XML文檔,它僅僅只是一堆文本而已,使用JSP創建XML文檔并不比創建一個HTML文檔難。
使用JSP發送XML內容就和發送HTML內容一樣。唯一的不同就是您需要把頁面的context屬性設置為text/xml。要設置context屬性,使用<%@page % >命令,就像這樣:
<%@ page contentType="text/xml" %>
接下來這個例子向瀏覽器發送XML內容:
<%@ page contentType="text/xml" %>
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
</books>
使用不同的瀏覽器來訪問這個例子,看看這個例子所呈現的文檔樹。
在使用JSP處理XML之前,您需要將與XML 和XPath相關的兩個庫文件放在\lib目錄下:
● XercesImpl.jar:在這下載http://www.apache.org/dist/xerces/j/
● xalan.jar:在這下載http://xml.apache.org/xalan-j/index.html
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>
<h3>Books Info:</h3>
<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>
訪問http://localhost:8080/main.jsp,運行結果如下:
BOOKS INFO:
The title of the first book is:Padam History
The price of the second book: 2000
使用JSP格式化XML
這個是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>
這個是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>
<h3>Books Info:</h3>
<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>
運行結果如下: