JSP XML

2018-03-20 14:14 更新

JSP教程 - JSP XML

從JSP發(fā)送XML

要將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

要使用JSP解析XML,請(qǐng)?jiān)谀?lt;Tomcat Installation Directory>\lib中安裝以下兩個(gè)XML和XPath庫:

首先,創(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。


使用XSLT在JSP中格式化/轉(zhuǎn)換XML

首先,創(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>
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)