Home > Articles > Web Services > XML

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020