To send XML data as a page back to client, set the content type of your page to text/xml.
<%@ page contentType="text/xml" %>
Full code:
<%@ page contentType="text/xml" %>
<books>
<book>
<name>JSP</name>
<author>java2s.com</author>
<price>123</price>
</book>
</books>
To parse XML using JSP, install the following two XML and XPath libraries into your <Tomcat Installation Directory>\lib:
XercesImpl.jar from http://www.apache.org/dist/xerces/j/
xalan.jar from http://xml.apache.org/xalan-j/index.html
First, create the books.xml file as follows:
<books> <book> <name>JSP</name> <author>java2s.com</author> </book> <book> <name>Servlet</name> <author>java2s.com</author> </book> </books>
Create the following main.jsp in the same folder with the above xml file.
<%@ 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>
Access above JSP using http://localhost:8080/main.jsp.
First, create the following XSLT stylesheet 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>
Apply the above style sheet within JSP file.
<%@ 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>java2s.com</author> <price>100</price> </book> <book> <name>Servlet</name> <author>java2s.com</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>