要將XML數(shù)據(jù)作為頁面發(fā)送回客戶端,請(qǐng)將頁面的內(nèi)容類型設(shè)置為text/xml。
<%@ page contentType="text/xml" %>
完整代碼:
<%@ page contentType="text/xml" %> <books> <book> <name>JSP</name> <author>hgci.cn</author> <price>123</price> </book> </books>
要使用JSP解析XML,請(qǐng)?jiān)谀?lt;Tomcat Installation Directory>\lib中安裝以下兩個(gè)XML和XPath庫:
XercesImpl.jar 來自 http://www.apache.org/dist/xerces/j/
xalan.jar 來自 http://xml.apache.org/xalan-j/index.html
首先,創(chuàng)建books.xml文件,如下所示:
<books> <book> <name>JSP</name> <author>hgci.cn</author> </book> <book> <name>Servlet</name> <author>hgci.cn</author> </book> </books>
在與上述xml文件相同的文件夾中創(chuàng)建以下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> <body> <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" /> </body> </html>
使用http://localhost:8080/main.jsp訪問上面的JSP。
首先,創(chuàng)建以下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>
在JSP文件中應(yīng)用上述樣式表。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <html> <body> <c:set var="xmltext"> <books> <book> <name>JSP</name> <author>hgci.cn</author> <price>100</price> </book> <book> <name>Servlet</name> <author>hgci.cn</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>
更多建議: