Moderate

While all the XML/XSL processing can be done on the client side and the HTML pages loaded to the Web server as described in the Modest example, that is not really an efficient or preferred way to manage a Web site using XML. It's better to load the XML and XSL files to the Web server and let it do the processing to produce the pages for the Web site. Outlined below are some simple ways to do this using different scripts applicable to different server environments.

While the scripts below are simple, they do have drawbacks in requiring one to "hardcode" the name of the XML file and XSL file in the code. One would need to repeat this script for every XML and XSL file used and for every HTML page produced. (In effect, three files would be used -- .xml, .xsl, and .asp (or .php, .jsp, etc.) -- for every .html page produced.) Plus, it doesn't allow for the processing of parameters passed between the Web page (either in the URL QueryString or via a form) and the XSL file. Luckily, some enhancements can be made to the basic script to work around these restrictions. The Elaborate examples detail some of these enhancements.

Use any of the simple scripts below to load and process XML and XSL files on the Web server and return HTML pages to the visitor's browser. The scripts all work in a similar fashion, but geared to their particular environments. Special consderations for each script are provided in the paragraph preceding the example script.


A Simple ASP script (using VBScript)

Insert the name of the XML file in the "oXML.load" line and the name of the XSL file in the "oXSL.load" line. The example here uses "index.xml" and "index.xsl." The ASP file is saved as "index.asp" and loaded to the Web server along with the index.xml and index.xsl files to produce the Home Page. Note that this script is based on ASP 3.0 using VBScript. For more information on ASP, see http://www.4guysfromrolla.com/. For more information on the example used here, see http://www.topxml.com/wap/articles/wap_xml_xsl/wml2text6.asp

				
<%@ Language=VBScript %>
<%
  Dim oXML, oXSL
  Set oXML = CreateObject("MSXML2.DOMDocument")
  oXML.load(Server.MapPath("index.xml"))
  Set oXSL = CreateObject("MSXML2.DOMDocument")
  oXSL.load(Server.MapPath("index.xsl"))
  Response.write oXML.transformNode(oXSL)
%>

			

A Simple ASP.NET script (using C#)

Insert the name of the XML file in the "xmlPath = Server.MapPath" line and the name of the XSL file in the "xslPath = Server.MapPath" line. The example here uses "index.xml" and "index.xsl." The ASPX file is saved as "index.aspx" and loaded to the Web server along with the index.xml and index.xsl files to produce the Home Page. Note that this script is based on ASP.NET using C#. For more information on ASP.NET, see http://msdn.microsoft.com/asp.net/. For more information on the example used here, see http://www.topxml.com/xsl/articles/dotnet_xslt/default.asp

				
<%@ Page Language="C#" Debug="false" %>

<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<%@ Import Namespace="System.Xml.XPath" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>

<script language="C#" runat="server">

/* This function is called every time when aspx page loads */
public void Page_Load(Object sender, EventArgs E) 

//Load the XML and XSL files into variables.
string xmlPath;
string xslPath; 
xmlPath = Server.MapPath("index.xml");
xslPath = Server.MapPath("index.xsl"); 

//Read the XML file
FileStream fs = new FileStream(xmlPath,FileMode.Open,FileAccess.Read);
StreamReader reader = new StreamReader(fs,Encoding.UTF8);
XmlTextReader xmlReader = new XmlTextReader(reader);

//Instantiate the XPathDocument Class
XPathDocument doc = new XPathDocument(xmlReader);

//Instantiate the XslTransform Class
XslTransform xslDoc = new XslTransform();
xslDoc.Load(xslPath);
xslDoc.Transform(doc,null,Response.Output);

//Close Readers
reader.Close();
xmlReader.Close();
}

</script>

			

A Simple PHP script

Insert the name of the XML file in the "$inputdom->load" line and the name of the XSL file in the "$xsl->load" line. The example here uses "index.xml" and "index.xsl." The PHP file is saved as "index.php" and loaded to the Web server along with the index.xml and index.xsl files to produce the Home Page. Note that this only works with PHP5. For more information on PHP, see http://www.zend.com/php5/. For more information on the example used here, see http://www.zend.com/php5/articles/php5-xmlphp.php

				
<?php
/* create a DomDocument object, and then load the XML file */
$inputdom = new DomDocument();
$inputdom->load("index.xml");
/* create a DomDocument object, and then load the XSL file */
$xsl = new DomDocument();
$xsl->load("index.xsl");
/* create the processor and import the stylesheet */
$proc = new XsltProcessor();
$xsl = $proc->importStylesheet($xsl);
/* transform and output the xml document */
$newdom = $proc->transformToDoc($inputdom);
print $newdom->saveXML();
?>

			

A Simple JSP script

Insert the name of the XML and XSL files in the "<xtags:style>" line. The example here uses "index.xml" and "index.xsl." The JSP file is saved as "index.jsp" and loaded to the Web server along with the index.xml and index.xsl files to produce the Home Page. Note that this only works when you specify the jsp tag library, "xtags," and have it installed correctly. For more information on JSP, see http://java.sun.com/products/jsp/. For more information on the JSP xtag library, see http://jakarta.apache.org/taglibs/doc/xtags-doc/intro.html

				
<%-- Must specify the jsp tag library -- xtags and make sure it has been installed correctly   --%>
<%@ taglib uri="http://jakarta.apache.org/taglibs/xtags-1.0" prefix="xtags" %>
     <xtags:style  xml="index.xml" xsl="index.xsl">
     </xtags:style>

			

A Simple Java Filter

Insert the name of the XML file in the "xmlData = " line, and the name of the XSL file in the "styleSheet= " line. The example here uses "index.xml" and "index.xsl." The Java Filter is compiled and saved as a Java class file and loaded to the Web server in the "/WEB-INF/classes" subdirectory. A "web.xml" file must also be saved in the "WEB-INF" directory to identify the Java Filter class name and the URL's associated with it. You must also save a blank index.jsp file along with the index.xml and index.xsl files to produce the Home Page. For more information on Java Filters, see http://java.sun.com/products/servlet/Filters.html.


import java.io.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public  class ManageXMLXSL implements Filter 
{

   private FilterConfig filterConfig = null;

   public void init(FilterConfig filterConfig) throws ServletException 
   {
      this.filterConfig = filterConfig;
   }

   public void destroy() 
   {
      this.filterConfig = null;
   }

   /*******************************************************************************************
     This doFilter method is the key function which do all the required work
   *******************************************************************************************/
   public void doFilter(ServletRequest request, 
          ServletResponse response, FilterChain chain)
           throws IOException, ServletException 
   {

     String contentType;
     contentType = "text/html";

	  /* Assign xml and xsl file names to declared variables */
     String styleSheet;
     String xmlData;
     xmlData = "index.xml";
     styleSheet = "index.xsl";
       
     response.setContentType(contentType);

      /* set XSL style sheet */
     String stylePath =filterConfig.getServletContext().getRealPath(styleSheet);
     Source styleSource = new StreamSource(stylePath);

      /* set xml data source */
     String xmlPath =filterConfig.getServletContext().getRealPath(xmlData);
     Source xmlSource = new StreamSource(xmlPath);

     PrintWriter out = response.getWriter();

     chain.doFilter(request, response);

     /* Do the translation */
     try 
     {
      TransformerFactory transformerFactory =TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer(styleSource); 
      CharArrayWriter caw = new CharArrayWriter();
      StreamResult result  = new StreamResult(caw);
      transformer.transform(xmlSource, result);
      response.setContentLength(caw.toString().length());
      out.write(caw.toString());
     } 
     catch(Exception ex) 
     {
      out.println(ex.toString());
     }

  }  //End of doFilter

}  //End of class

			

A Simple ColdFusion Script

Insert the paths and names of the XML and XSL files in the "<cffile>" tags. The example here uses "index.xml" and "index.xsl." Save the file as index.cfm along with the index.xml and index.xsl files to produce the Home Page. Note that this only works with ColdFusion MX 7. For more information on ColdFusion, see http://www.adobe.com/products/coldfusion/.


<!---********************************************************************************
* Finds the xml and xsl files on the server and reads them into variables
* Runs the XMLTransform function to process the XML and XSL files, 
* Outputs the transformed XML as HTML			
*************************************************************************************--->
<cffile action="read" file=C:\CFusionMX7\wwwroot\index.xml" variable="mydoc">
<cffile action="read" file="C:\CFusionMX7\wwwroot\index.xsl" variable="xslDoc">
<cfset transformedXML = XmlTransform(mydoc, xslDoc)>
<cfoutput> #transformedXML# </cfoutput>

			

A Simple Dreamweaver Script (Using ColdFusion)

Insert the names of the XML and XSL files in the "<cfinvokeargument>" tags. The example here uses "index.xml" and "index.xsl." Save the file as index.cfm along with the index.xml and index.xsl files to produce the Home Page. Two different approaches using the same code are shown below: the first creates an entire HTML page from the XML/XSL file; the second inserts XML/XSL processing within an existing HTML page. The difference is that the second approach enables you to use XML/XSL within existing Dreamweaver templates and HTML pages to process portions of the Web page that lend themselves to XML/XSL processing. For example, the text of newsletter pages that are commonly formatted and displayed in similar ways could be produced via these XML/XSL insertions. All the newsletters' text may be contained in one XML file and transformed by one XSL file that selects the specific newsletter content for that Web page. Rather than creating dozens or even hundreds of separate HTML pages to display these specific newsletters, this one file can create them all dyanamically and consistently based on users' requests from their Web browsers. Note that this only works with Dreamweaver 8 and this example uses ColdFusion as its application server. For more information on Dreamweaver, see http://www.adobe.com/products/dreamweaver/.


 <!--- *************************************************************
				          EXAMPLE 1
 Within Dreamweaver, you can use ColdFusion tags
 to load and process XML/XSL files that produce the
 complete HTML page as seen in the example below 
 ************************************************************** --->
<cfinvoke
  component="includes.MM_XSLTransform.MM_XSLTransform"
  method="transform"
  returnvariable="mm_xsl_output">
  <!--- XSL Transformation --->
  <cfinvokeargument name="xml" value="index.xml">
  <cfinvokeargument name="xsl" value="index.xsl">
</cfinvoke>

 <!--- *************************************************************
 				          EXAMPLE 2
 Within Dreamweaver, you can insert the same 
 ColdFusion  tags used in the example above
 to load and process XML/XSL files within an existing
HTML page as seen in the example below 
 ************************************************************** --->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style media="screen" type="text/css">
						@import "master.css"; /* main css template */
				</style>
</head>

<body>
<h1>THIS IS STRAIGHT HTML</h1>
<p>The text below is inserted XML/XSL</p> 
<cfinvoke
  component="includes.MM_XSLTransform.MM_XSLTransform"
  method="transform"
  returnvariable="mm_xsl_output">
  <!--- XSL Transformation --->
  <cfinvokeargument name="xml" value="index.xml">
  <cfinvokeargument name="xsl" value="index.xsl">
</cfinvoke>
</body>

</html>

			

A Simple Cocoon Script

Apache Cocoon is a web development framework built around the concepts of separation of concerns and component-based web development. Cocoon implements these concepts around the notion of 'component pipelines', each component on the pipeline specializing on a particular operation. This makes it possible to use a Lego(tm)-like approach in building web solutions, hooking together components into pipelines without any required programming.

A simple Cocoon approach is to insert the paths and names of the XML and XSL files in the "<map:generate src="xmlfilename'>" and "<map:transform src="xslfilename">" tags within a sitemap file that controls the Web site. The example here uses "index.xml" and "index.xsl." Save this pipeline in a sitemap.xmap file along with the index.xml and index.xsl files to produce the Home Page. This is a simplified version of the Cocoon sitemap. For more information on Cocoon, see http://cocoon.apache.org/.


<!---********************************************************************************
* Finds the xml and xsl files on the server, transforms them, and 
* Outputs the transformed XML as HTML			
*************************************************************************************--->
<map:pipeline>
 <map:match pattern="index">
  <map:generate src="index.xml"/>
  <map:transform src="index.xsl"/>
  <map:serialize type="html"/>
 </map:match>
</map:pipeline>