Back to: JSP Tutorials for Beginners and Professionals
Generating XML from JSP and JavaBeans
In this article, I am going to discuss How to Generate XML from JSP and JavaBeans with Examples. Please read our previous article where we discussed How to Work with XML in JSP Application.
How to Generate XML from JSP and JavaBeans?
We can retrieve the XML data from a JavaBeans component. In the below example, BookBean.java is the JavaBean component that defines a bean with the books data. Then the books.jsp page will generate an XML document where the data is retrieved from BookBean.
Book.java
package books; public class Book implements java.io.Serializable { private String name; private String author; private float price; public Book (String name, String author, float price) { this.name = name; this.author = author; this.price = price; } public String getName () { return name; } public String getAuthor () { return author; } public float getPrice () { return price; } }
Bookbean.java
package books; import java.util.*; public class BookBean implements java.io.Serializable { private Vector books = new Vector(); public BookBean () { books.addElement (new Book ("Padam History", "ZARA", (float) 100)); books.addElement (new Book ("Great Mistry", "NUHA", (float) 2000)); } public Iterator getBooks() { return books.iterator(); } }
books.jsp
<%@ page contentType="text/xml"%> <%@ page import="books.*"%> <jsp:useBean id="books" class="books.BookBean" /> <% java.util.Iterator b = books.getBooks(); Book book = null; %> <?xml version="1.0" encoding="UTF-8"?> <books> <% while (b.hasNext()) { %> <% book = (Book) b.next(); %> <book> <name><%= book.getName() %></name> <author><%= book.getAuthor() %></author> <price><%= book.getPrice() %></price> </book> <% } %> </books>
Output
Now request the books.jsp page from the browser that supports XML, you will get the following output:
Now, let’s replace the line <?xml version=”1.0″ encoding=”UTF-8″?> with a line that specifies a stylesheet <?xml:stylesheet type=”text/xsl” href=”http://localhost:8086/JSPDemo/books.xml” version=”1.0″ encoding=”UTF-8″?> , the XML document will be generated and the XSL stylesheet will be applied and you can see the following output:
Transforming XML
To transform XML into any desired format XSTL can be used. The processor takes XML document as input and uses XSL transformation stylesheet to create a new document format.
Example
In this example, XmlToHtmlTransformer.java shows how to transform the XML document (books.xml) into an HTML document (books.html). Here, books.xml is the input file that will be transformed into books.html based on the stylesheet style.xsl.
XmlToHtmlTransformer.java
package books; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class XmlToHtmlTransformer { public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { transform("books.xml", "style.xsl"); } public static void transform(final String xml, final String xslt) throws SAXException, IOException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { ClassLoader classloader = XmlToHtmlTransformer.class.getClassLoader(); InputStream xmlData = classloader.getResourceAsStream(xml); URL xsltURL = classloader.getResource(xslt); Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlData); Source stylesource = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm()); Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource); StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(xmlDocument), new StreamResult(stringWriter)); // write to file File file = new File("books.html"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write(stringWriter.toString()); bw.close(); } }
books.xml
<?xml version="1.0" encoding="UTF-8"?> <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>
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>
The generated HTML file (books.html) is:
books.html
<html> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 50%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <h2>Books</h2> <table> <tr> <th>Name</th><th>Author</th><th>Price</th> </tr> <tr> <td>Padam History</td><td>ZARA</td><td>100</td> </tr> <tr> <td>Great Mistry</td><td>NUHA</td><td>2000</td> </tr> </table> </body> </html>
Output:
In the next article, I am going to discuss Converting XML to Server-Side Objects. Here, in this article, I try to explain Generating XML from JSP and JavaBeans with Examples and I hope you enjoy this Generating XML from JSP and JavaBeans with Examples.