Java Tutorial/JSP/XML Transform
JSTL XML Transform
students.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<students>
<student id="1">
<name>
<first>A</first>
<last>B</last>
<middle>T</middle>
</name>
<grade>
<points>88</points>
<letter>B</letter>
</grade>
</student>
<student id="2">
<name>
<first>C</first>
<last>D</last>
<middle>K</middle>
</name>
<grade>
<points>92</points>
<letter>A</letter>
</grade>
</student>
<student id="3">
<name>
<first>E</first>
<last>F</last>
<middle>A</middle>
</name>
<grade>
<points>72</points>
<letter>C</letter>
</grade>
</student>
</students>
Performing XSL Transformations
<%@ page language="java" contentType="text/html" %>
<%@ page pageEncoding="UTF-8"%>
<%@ page import="javax.xml.transform.*"%>
<%@ page import="javax.xml.transform.stream.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Customer Orders</title>
</head>
<body>
<h1>Customer Orders</h1>
<%! String FS = System.getProperty("file.separator"); %>
<%
String xmlFile = request.getParameter("XML");
String xslFile = request.getParameter("XSL");
String ctx = getServletContext().getRealPath("") + FS;
xslFile = ctx + xslFile;
xmlFile = ctx + xmlFile;
TransformerFactory tFactory =
TransformerFactory.newInstance();
Transformer transformer =
tFactory.newTransformer(new StreamSource(xslFile));
transformer.transform(
new StreamSource(xmlFile), new StreamResult(out));
%>
</body>
</html>
XML transformation
<%@ page import="javax.xml.transform.*, javax.xml.transform.stream.*, java.io.*" %>
<%
try
{
TransformerFactory transformerfactory = TransformerFactory.newInstance();
Transformer transformer = transformerfactory.newTransformer(new StreamSource(new File
(application.getRealPath("/") + "your.xsl")));
transformer.transform(new StreamSource(new File(application.getRealPath("/") + "your.xml")),
new StreamResult(new File(application.getRealPath("/") + "your.html")));
}
catch(Exception e) {}
FileReader filereader = new FileReader(application.getRealPath("/") + "your.html");
BufferedReader bufferedreader = new BufferedReader(filereader);
String instring;
while((instring = bufferedreader.readLine()) != null) {
%>
<%= instring %>
<%
}
filereader.close();
%>