Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Creating the Template in ASP

All of the logic that goes into creating the template is applied to the main page after we load the original style sheet, but before we actually use it. Let's take it one step at a time. First, we go ahead and load the documents as usual, with one small change:

<%@ language = "VBSCRIPT" %>
<% 
...  
 'Create DOM Documents
 set source = Server.CreateObject("Msxml2.FreeThreadedDOMDocument")
 source.load(sourceFile) 
 
 set style = Server.CreateObject("Msxml2.FreeThreadedDOMDocument")
 style.async = false
 style.load(styleFile) 

...

Because we will manipulate the style document object, we want to make sure that each operation is complete before the next begins. To do that, we'll turn off asynchronous processing by setting the async property to false.

Next, we'll establish the basic building blocks:

...
 set style = Server.CreateObject("Msxml2.FreeThreadedDOMDocument")
 style.async = false
 style.load(styleFile) 

 'Get the style sheet root element
 set styleRoot = style.documentElement

 'Create the basic elements
 set templateElement = style.createElement("xsl:template")
 call templateElement.setAttribute("match", "content")
 set tableElement = style.createElement("table") 
 set newsRowElement = style.createElement("tr")
 set weatherTVRowElement = style.createElement("tr")
  
 set midRowElement = style.createElement("tr")
 set midRowCellElement = style.createElement("td")
 call midRowCellElement.setAttribute("colspan", "2")
 call midRowCellElement.appendChild(style.createElement("hr"))
 call midRowElement.appendChild(midRowCellElement)
...

First, we determine the root element of the style document, the xsl:stylesheet element. When the new template is built, we'll append it to this element.

Next, we'll create the basic elements with the names and attributes they'll need later. These include the xsl:template element and the table rows and columns.

NOTE

Strictly speaking, xsl:template is not the name of the element; it is the name and the namespace alias.

Next, we'll create the pieces that will be added to the table:

...
 call midRowCellElement.appendChild(style.createElement("hr"))
 call midRowElement.appendChild(midRowCellElement)

 'Create the "apply-templates" elements
 set weatherElementCell = style.createElement("td")
 call weatherElementCell.setAttribute("valign", "top")
 set weatherElement = style.createElement("xsl:apply-templates")
 call weatherElement.setAttribute("select", "weather")
 call weatherElementCell.appendChild(weatherElement)
 
 set schedulesElementCell = style.createElement("td")
 call schedulesElementCell.setAttribute("valign", "top")
 set schedulesElement = style.createElement("xsl:apply-templates")
 call schedulesElement.setAttribute("select", "schedules")
 call schedulesElementCell.appendChild(schedulesElement)
 
 set newsElementCell = style.createElement("td")
 set newsElement = style.createElement("xsl:apply-templates")
 call newsElement.setAttribute("select", "gossip")
 call newsElementCell.appendChild(newsElement)
 call newsElementCell.setAttribute("colspan", "2")
 call newsRowElement.appendChild(newsElementCell)
...

Here, we create a number of table cells, along with their content. Ultimately, we'll add them to the table according to the user's choices, but first we need to retrieve those choices:

... 
 call newsElementCell.setAttribute("colspan", "2")
 call newsRowElement.appendChild(newsElementCell)

 'Get user choices
 news = Request.Cookies("news")
 if news = "" then news = "bottom"
 
 tvlistings = Request.Cookies("tvlistings")
 if tvlistings = "" then tvlistings = "right"
 
 weather = Request.Cookies("weather")
 if weather = "" then weather = "left"
 
 weatherlocation = Request.Cookies("weatherlocation")
 if weatherlocation = "" then weatherlocation = "Tampa, FL"
...

This section is straightforward—simply setting variables according to the cookies present. If a particular cookie doesn't exist, we substitute default values.

Now we're ready to actually build the document:

...  
 weatherlocation = Request.Cookies("weatherlocation")
 if weatherlocation = "" then weatherlocation = "Tampa, FL"

 'Build weather/listings row
 if weather = "left" then
  call weatherElementCell.setAttribute("class", "leftcell") 
  call weatherTVRowElement.appendChild(weatherElementCell)
 elseif tvlistings = "left" then
  call schedulesElementCell.setAttribute("class", "leftcell")
  call weatherTVRowElement.appendChild(schedulesElementCell)
 end if
  
 if tvlistings = "right" then
  call schedulesElementCell.setAttribute("class", "rightcell")
  call weatherTVRowElement.appendChild(schedulesElementCell)
 elseif weather = "right" then
  call weatherElementCell.setAttribute("class", "rightcell") 
  call weatherTVRowElement.appendChild(weatherElementCell)
 end if
...

First, we'll build the row that contains the weather and TV listings. Because of the way HTML interprets a table, the order is important; we must add the left cell first. Once the row is built, we can complete the table:

...
  call weatherTVRowElement.appendChild(weatherElementCell)
 end if
 
 'Complete the table
 if news = "none" then
  if weather <> "none" or tvlistings <> "none" then
   call tableElement.appendChild(weatherTVRowElement)
  end if
 elseif news = "top" then
  call newsRowElement.setAttribute("class", "toprow")
  call tableElement.appendChild(newsRowElement)
  if weather <> "none" or tvlistings <> "none" then
   call tableElement.appendChild(midRowElement)
   call weatherTVRowElement.setAttribute("class", "bottomrow")
   call tableElement.appendChild(weatherTVRowElement)
  end if
 elseif news = "bottom" then
  if weather <> "none" or tvlistings <> "none" then
   call weatherTVRowElement.setAttribute("class", "toprow")
   call tableElement.appendChild(weatherTVRowElement)
   call tableElement.appendChild(midRowElement)
  end if
  call newsRowElement.setAttribute("class", "bottomrow")
  call tableElement.appendChild(newsRowElement)
 end if 
...

In many situations, it wouldn't matter if we added empty elements to a document, but because empty cells and rows can disrupt the flow of the page, we need to be sure content exists (or should exist) before we add it to the document.

If the user has indicated that he or she doesn't want any news on his or her page, we simply check for weather or TV listings; if either exists, we add the row to the table.

If the news is to appear on the top of the page, we set the class attribute on the news row element and then add the news row to the table. The middle row, with the horizontal rule, should appear only if both rows are present, so we'll include that in the check for weather or TV listings, which are also added to the table. If the news is to appear on the bottom, the situation is reversed.

When all is said and done, the table element is complete, and needs only to be added to the document:

...
  call newsRowElement.setAttribute("class", "bottomrow")
  call tableElement.appendChild(newsRowElement)
 end if 

 'Add the table to the template and the template to the document
 call templateElement.appendChild(tableElement)
 call styleRoot.appendChild(templateElement)
...

First, we add the table to the template element and then the template element to the root element of the style sheet document.

In an ideal world, we could now use the style document object to transform the document, but unfortunately, this is not an ideal world. The xsl: notation at the beginning of style sheet element tag names is actually a namespace alias, and not a part of the actual name; so if we attempt to transform the document now, we will get an error. Ideally, we would set the name of the element as, say, template and then set the namespace; but until we can do that, we can use a simple workaround:

...
 call templateElement.appendChild(tableElement)
 call styleRoot.appendChild(templateElement)

 'Save and reload the document
 Application.Lock
 style.save(server.MapPath("temp.xsl"))
 style.load(server.MapPath("temp.xsl"))
 Application.Unlock
...

Simply put, all we are doing here is to save the document as we've built it and then immediately reload it. When we do that, the names and namespaces are interpreted properly, solving the problem. To prevent problems of one user overwriting another, we lock the application until we've reloaded the document. After that, we don't care what happens to the temporary file.

At this point, we're almost ready to perform the transformation. We have one more piece of customization to add, which we'll discuss in the next section.

Creating the Template in Java

Most of the logic and methodology for creating the template using Java is the same as it was using ASP, but important differences in main.java exist. Syntax issues are obvious, but there are also structural issues.

A minor difference is that because of the way cookies are set to the servlet, we should retrieve our user choices much earlier in the process—when we check for the overall style sheet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class main extends HttpServlet {

  public void doGet(HttpServletRequest request, 
           HttpServletResponse response)
  throws IOException, ServletException
  {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
      //Set source files
      String XMLFileName = "http://localhost/";
      if (request.getParameter("content")== null) {
       XMLFileName = XMLFileName + "content.xml";
      } else {
       XMLFileName = XMLFileName + request.getParameter("content");
      }
      StreamSource source = new StreamSource(XMLFileName);
		  
      String XSLFileName = "";
      String news = "";
      String tvlistings = "";
      String weather = "";
      String weatherlocation = "";

      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
       for (int i = 0; i < cookies.length; i++) {
         Cookie thisCookie = cookies[i];
         if (thisCookie.getName().equals("stylechoice")){
          XSLFileName = 
             "http://localhost/"+thisCookie.getValue();
         }
         if (thisCookie.getName().equals("news")){
          news = thisCookie.getValue();
         }
         if (thisCookie.getName().equals("tvlistings")){
          tvlistings = thisCookie.getValue();
         }
         if (thisCookie.getName().equals("weather")){
          weather = thisCookie.getValue();
         }
         if (thisCookie.getName().equals("weatherlocation")){
          weatherlocation = thisCookie.getValue();
         }
       }
      }

      if (news.equals("")) { news = "bottom"; }
      if (tvlistings.equals("")) { tvlistings = "right"; }
      if (weather.equals("")) { weather = "left"; }
      if (weatherlocation.equals("")) { weatherlocation = "Tampa, FL"; }
... 

If we don't find the cookies we're looking for, we'll set the default values, just as we did before.

There is a structural change even more important than checking the cookies, however. In ASP, we created a transformation by loading the source and style as documents, so we could work with the style Document object directly to add the new template. In Java, however, we are using StreamSources, which means that the application is streaming the data directly from the file. In order to work with a Document object, we need to parse the style sheet file to create one:

...
      if (weather.equals("")) { weather = "left"; }
      if (weatherlocation.equals("")) { weatherlocation = "Tampa, FL"; }

      if (XSLFileName.equals("")) {
       XSLFileName = "http://localhost/style1.xsl";
      }
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document styleDoc = db.parse(XSLFileName);		  
...

Note that we removed the creation of the style StreamSource. Once the base style sheet file has been determined by the cookie (or by using the default value), we create a DocumentBuilderFactory, which allows us to create the DocumentBuilder and parse the file. Make sure to tell the factory that we want any parsers to be "namespace-aware," so we can add style sheet elements without the same problems we had in ASP.

Once we have the document, the process of building the new Elements is exactly the same as it was in ASP, with the obvious syntax changes:

...
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document styleDoc = db.parse(XSLFileName);		  

      //Get the style sheet root element
      Node styleRoot = styleDoc.getDocumentElement();

      //Create the basic elements
      Element templateElement = 
           styleDoc.createElementNS("http://www.w3.org/1999/XSL/Transform", 
                       "xsl:template");
      templateElement.setAttribute("match", "content");
      Element tableElement = styleDoc.createElement("table");
      Element newsRowElement = styleDoc.createElement("tr");
      Element weatherTVRowElement = styleDoc.createElement("tr");
  
      Element midRowElement = styleDoc.createElement("tr");
      Element midRowCellElement = styleDoc.createElement("td");
      midRowCellElement.setAttribute("colspan", "2");
      midRowCellElement.appendChild(styleDoc.createElement("hr"));
      midRowElement.appendChild(midRowCellElement);

      //Create the "apply-templates" elements
      Element weatherElementCell = styleDoc.createElement("td");
      weatherElementCell.setAttribute("valign", "top");
      Element weatherElement = 
           styleDoc.createElementNS("http://www.w3.org/1999/XSL/Transform", 
                       "xsl:apply-templates");
      weatherElement.setAttribute("select", "weather");
      weatherElementCell.appendChild(weatherElement);
 
      Element schedulesElementCell = styleDoc.createElement("td");
      schedulesElementCell.setAttribute("valign", "top");
      Element schedulesElement = 
           styleDoc.createElementNS("http://www.w3.org/1999/XSL/Transform", 
                       "xsl:apply-templates");
      schedulesElement.setAttribute("select", "schedules");
      schedulesElementCell.appendChild(schedulesElement);
 
      Element newsElementCell = styleDoc.createElement("td");
      Element newsElement = 
           styleDoc.createElementNS("http://www.w3.org/1999/XSL/Transform", 
                       "xsl:apply-templates");
      newsElement.setAttribute("select", "gossip");
      newsElementCell.appendChild(newsElement);
      newsElementCell.setAttribute("colspan", "2");
      newsRowElement.appendChild(newsElementCell);
 
      //Build weather/listings row
      if (weather.equals("left")) {
       weatherElementCell.setAttribute("class", "leftcell");
       weatherTVRowElement.appendChild(weatherElementCell);
      } else if (tvlistings.equals("left")) {
       schedulesElementCell.setAttribute("class", "leftcell");
       weatherTVRowElement.appendChild(schedulesElementCell);
      }
 	
      if (tvlistings.equals("right")) {
       schedulesElementCell.setAttribute("class", "rightcell");
       weatherTVRowElement.appendChild(schedulesElementCell);
      } else if (weather.equals("right")) {
       weatherElementCell.setAttribute("class", "rightcell");
       weatherTVRowElement.appendChild(weatherElementCell);
      }
	
      //Complete the table
      if (news.equals("none")) {
       if (!weather.equals("none") || !tvlistings.equals("none")) {
         tableElement.appendChild(weatherTVRowElement);
       }
      } else if (news.equals("top")) {
       newsRowElement.setAttribute("class", "toprow");
       tableElement.appendChild(newsRowElement);
       if (!weather.equals("none") || !tvlistings.equals("none")) {
         tableElement.appendChild(midRowElement);
         weatherTVRowElement.setAttribute("class", "bottomrow");
         tableElement.appendChild(weatherTVRowElement);
       }
      } else if (news.equals("bottom")) {
       if (!weather.equals("none") || !tvlistings.equals("none")) {
         weatherTVRowElement.setAttribute("class", "toprow");
         tableElement.appendChild(weatherTVRowElement);
         tableElement.appendChild(midRowElement);
       }
       newsRowElement.setAttribute("class", "bottomrow");
       tableElement.appendChild(newsRowElement);
      }

      //Add the table to the template and the template to the document
      templateElement.appendChild(tableElement);
      styleRoot.appendChild(templateElement);
...

Notice that we are specifically using the createElementNS() method to add the style sheet elements properly.

Once we have the completed Document object, we want to create a DOMSource rather than a StreamSource, and use it in the final transformation:

...  
      templateElement.appendChild(tableElement);
      styleRoot.appendChild(templateElement);
	  
	  DOMSource style = new DOMSource(styleDoc);	
		  
      //Designate that the result goes to the browser;
      //StreamResult takes a Writer object.
      StreamResult result = new StreamResult(out);

      //Create the XSL processor
      TransformerFactory transFactory = TransformerFactory.newInstance();
      Transformer transformer = transFactory.newTransformer(style);

      //Transform the document
      transformer.transform(source, result);
  
   } catch (Exception e) {
     out.print(e.getMessage());
     e.printStackTrace();
   }
  }
}
  • + Share This
  • 🔖 Save To Your Account