Home > Articles

This chapter is from the book

This chapter is from the book

Programming Within a Style Sheet

In this section, we're going to leave the application alone and look at the style sheet itself.

The XSLT 1.0 Recommendation allows developers to create extension functions and elements that perform sophisticated programming. For example, we could duplicate the vote counting programming from Chapter 5 using just extensions built into the style sheet itself. Rather than creating an application to count the votes, we could simply transform the file.

Extensions can be handy because they allow sophisticated programming that can be carried out anywhere an appropriate transformation engine is available, rather than requiring a number of different applications. For example, IBM's developerWorks site (http://www.ibm.com/developerworks/) receives tutorials from authors in XML. A single transformation (spanning several XSLT style sheets) not only converts the single XML document into individual HTML pages for each tutorial panel, it also moves images into their proper folder, creates PDF files (in two sizes) and makes a ZIP file of all the HTML pages and graphics.

Before going any further, check the documentation for your XSL transformation engine to see whether any additional setup is required. For example, Java's transformation engine requires that bsf.jar be part of the CLASSPATH if any language other than Java is used for the extensions. We're going to start with JavaScript, so we'll need not only bsf.jar (which is part of the Java distribution), but also js.jar, downloadable from http://www.mozilla.org/rhino/

Although extension elements and functions are defined within the XSLT 1.0 Recommendation, there is no guidance on how to actually implement them; different vendors may choose different approaches.

Extension Functions

When we talked about XPath in Chapter 9, we discussed XPath functions. These functions provide a way to perform an action on data. For example, Listing 10.22 shows a style sheet that simply outputs the first letter of each vote.

A Fortunate Choice

Fortunately, our candidates have names that start with different letters. We wouldn't get any useful information if Dregraal's opponent were named D'nx'w!

Listing 10.22 Using a Function

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="/">
  <xsl:apply-templates select="votes/voter" />
</xsl:template>

<xsl:template match="voter">
  <xsl:value-of select="substring(vote, 1, 1)"/>
</xsl:template>

</xsl:stylesheet>

When we request the value of this built-in function, it executes the appropriate operations and outputs any data returned by the function.

We can use this same principle to define and use custom functions, or extension functions.

In this case, we simply want to transform the votes.xml file using a single XSL file, votes.xsl. Update TransformFile.java to look like Listing 10.7, but with the appropriate filenames.

To use the functions, we'll need to create a new namespace for them so that the processor knows they're extensions, and not mistakes. We'll also create a component that not only explicitly lists the functions we'll be creating, but will eventually hold the appropriate code as well. Listing 10.23 shows the basic form, including references to the soon-to-be-built functions.

Listing 10.23 Creating the Functions

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:lxslt="http://xml.apache.org/xslt"
        xmlns:results="http://www.example.com/results"
        extension-element-prefixes="results"
        version="1.0">

<lxslt:component prefix="results" functions="addVote, getResults">
</lxslt:component>

<xsl:template match="/">

  <xsl:apply-templates select="votes/voter"/>
  <xsl:value-of select="results:getResults()"/>

</xsl:template>

<xsl:template match="voter">
  <xsl:value-of select="results:addVote(string(vote))"/>
</xsl:template>

</xsl:stylesheet>

Here we've created an overall extension namespace, aliased with lxslt, to house the elements necessary for actually creating the extension elements and functions. The second new namespace, results, differentiates the extension elements and functions and points back to the component via the prefix attribute. We'll also explicitly list the prefix for extension elements so the processor knows how to handle them.

The component element specifies the functions that are defined within (we'll get to that next).

The functions themselves are called just as an XPath function might be called, using data from the document as any necessary arguments. The first, getResults(), takes no argument, but returns a string to be output to the page—in this case, with the election results. The second, addVote(), takes the value of the vote element and passes it to a function.

The functions themselves are shown in Listing 10.24a.

Listing 10.24a Adding the Functions for a Java Implementation

...
 <lxslt:component prefix="results" functions="addVote, getResults">
  <lxslt:script lang="javascript">

    var sparkle, dregraal;
    sparkle = 0;
    dregraal = 0;

    function addVote (thisVote) {
     if (thisVote.equals("Sparkle")) {
       sparkle = sparkle + 1;
     } else {
       dregraal = dregraal + 1;
     }
     return null;
    }

   function getResults(){
     return "Sparkle: "+sparkle+" Dregraal: "+dregraal;
   }
  </lxslt:script>
 </lxslt:component>

<xsl:template match="/">

  <xsl:apply-templates select="votes/voter"/>
  <xsl:value-of select="results:getResults()"/>

</xsl:template>

<xsl:template match="voter">
  <xsl:value-of select="results:addVote(string(vote))"/>
</xsl:template>

</xsl:stylesheet>

In this case, we're using JavaScript and embedding the code right in the page. Notice that the functions share names with their extension counterparts, so finding the right function to use is simple.

When we call for the value of addVote, the addVote() function adds the appropriate value and returns null, so nothing is output. When the document is complete, the getResults() function, which simply outputs the appropriate value, is called.

In this way, we can perform actions on data that we can explicitly pass as an argument. Extension elements give us even more power.

C++ and Visual Basic .NET

Prior to version 4.0, MSXML did not include support for XSLT extensions at all. MSXML 4.0 supports extension functions (but not extension elements, which are discussed next) via the msxsl:script element. Listing 10.24b shows an example.

Listing 10.24b Implementing XSLT Extensions Using MSXML

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:msxsl="urn:schemas-microsoft-com:xslt"
        xmlns:results="http://www.example.com/results"
        version="1.0">

<msxsl:script implements-prefix="results" language="JScript"><![CDATA[

  var sparkle, dregraal;
  sparkle = 0;
  dregraal = 0;

  function addVote (thisVote) {
    if (thisVote == "Sparkle") {
      sparkle = sparkle + 1;
    } else {
      dregraal = dregraal + 1;
    }
    return '';
   }

   function getResults() {
     return "Sparkle: "+sparkle+" Dregraal: "+dregraal;
   }
]]></msxsl:script>

<xsl:template match="/">
  <xsl:apply-templates select="votes/voter"/>
  <xsl:value-of select="results:getResults()"/>
</xsl:template>

<xsl:template match="voter">
  <xsl:value-of select="results:addVote(string(vote))"/>
</xsl:template>

</xsl:stylesheet>

For documentation on the msxsl:script element, see the MSXML XSLT Reference Guide at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/htm/xsl_ref_overview_1vad.asp.

PHP and Perl

Sablotron can support JavaScript extensions, but it uses a different function namespace and format than that used in the preceding Java example. JavaScript extension functionality in Sablotron is also not built in by default; you must first install the Mozilla JavaScript library. (This is true even if you have Mozilla itself installed; the browser installation lacks the headers required to build against the library.) Then you must build both PHP and the Perl Sablotron wrapper module XML::Sablotron to explicitly link against the Mozilla JavaScript library as well as against Sablotron itself. It's not a process for the faint of heart; again, if you can find prebuilt binaries of Perl or PHP and Sablotron+JavaScript, you'll probably save yourself much frustration by using them.

Listing 10.24c shows a version of the XSL document in Listing 10.24b that will work with Sablotron.

Listing 10.24c Adding the Functions for Sablotron in PHP or Perl

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:func="http://www.exslt.org/functions"
      xmlns:results="http://www.example.com/results"
      extension-element-prefixes="func"
      exclude-result-prefixes="results">

<func:script implements-prefix="results" language="javascript"><![CDATA[

  var sparkle, dregraal;
  sparkle = 0;
  dregraal = 0;

  function addVote (thisVote) {
    if (thisVote == "Sparkle") {
      sparkle = sparkle + 1;
    } else {
      dregraal = dregraal + 1;
    }
    return '';
   }

   function getResults() {
     return "Sparkle: "+sparkle+" Dregraal: "+dregraal;
   }
]]>
<xsl:fallback>
 <xsl:text>Javscript extensions not supported</xsl:text>
</xsl:fallback>
</func:script>

<xsl:template match="/">
  <xsl:apply-templates select="votes/voter"/>
  <xsl:value-of select="results:getResults()"/>
</xsl:template>

<xsl:template match="voter">
  <xsl:value-of select="results:addVote(string(vote))"/>
</xsl:template>

</xsl:stylesheet>

The actual transformation is performed as usual.

Extension Elements

In the next section, we'll take a look at how extension elements enable us to use information about the context node, but first let's look at the elements themselves.

In Listing 10.25, we're turning the addVote function into an addVote element.

Listing 10.25 Creating an Extension Element

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:lxslt="http://xml.apache.org/xslt"
        xmlns:results="http://www.example.com/results"
        extension-element-prefixes="results"
        version="1.0">


 <lxslt:component prefix="results" functions="getResults" elements="addVote">
  <lxslt:script lang="javascript">
   var sparkle, dregraal;
   sparkle = 0;
   dregraal = 0;

   function addVote(ctx, elem) {
     if (elem.getAttribute("enforced") == "no") {
        return ("Voting restrictions not enforced.");
     } else {
        return ("Voting restrictions enforced.");
     }

     if (thisVote.equals("Sparkle")) {
       sparkle = sparkle + 1;
     } else {
       dregraal = dregraal + 1;
     }
     return null;
   }

   function getResults(){
     return "Sparkle: "+sparkle+" Dregraal: "+dregraal;
   }
  </lxslt:script>
 </lxslt:component>

<xsl:template match="/">

  <xsl:apply-templates select="votes/voter/vote"/>
  <xsl:value-of select="results:getResults()"/>

</xsl:template>

<xsl:template match="vote">
  <results:addVote enforced="yes"/>
</xsl:template>

</xsl:stylesheet>

We've made several changes here. First, we've told the component to treat addVote as an element rather than as a function, so we've changed the signature of addVote() to match that of a function linked to an extension element. We'll talk about the parameters in a moment.

The actual function itself has been changed to an extension element. No attributes are required for an extension element, but we're adding one: enforced. This attribute tells the script whether we're enforcing the rule that says only single beings and hosts can vote; symbionts are not allowed to vote.

In the script itself, the extension element is represented by the second parameter, in this case called elem. To get the value of the enforced attribute, we can use the getAttribute() method. This should look familiar; we're calling the same DOM Element getAttribute() method as before, but in JavaScript instead of Java or the other languages we've been looking at. The elem argument represents a plain old DOM Element object.

Finally, we made a slight change to the XPath expressions, for reasons we'll discuss after the next example.

If we were to execute this transformation, the results would look like this:

Voting restrictions enforced.Voting restrictions enforced.Voting restrictions
enforced.Voting restrictions enforced.Voting restrictions enforced.Sparkle: 0
Dregraal: 0

For every vote, the addVote element was accessed, so the addVote() function was called. It output the results of the element test, but no votes were actually added, so the tally is inaccurate.

Next, let's look at that tally.

Element Context

Upon first reflection, you may be wondering how we're going to pass in the vote information if there's no parameter for it, as there was when we were creating custom functions. In fact, there is a way to pass this information to the script: the context node.

At any point during the transformation of a document, a single node acts as the context node. When the style sheet asks for text, it's looking for the text of the context node. When it asks for a child element, it's referring to a child of that node.

We'll pass this context node into the extension element's function, as shown in Listing 10.26.

Listing 10.26 Using Context

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:lxslt="http://xml.apache.org/xslt"
        xmlns:results="http://www.example.com/results"
        extension-element-prefixes="results"
        version="1.0">

 <lxslt:component prefix="results" functions="getResults" elements="addVote">
  <lxslt:script lang="javascript">

   var sparkle, dregraal;
   sparkle = 0;
   dregraal = 0;

   function addVote(ctx, elem) {
    ctxNode = ctx.getContextNode();
    vote = ctxNode.getFirstChild().getNodeValue();
    if (elem.getAttribute("enforced") == "no") {
       //Just add votes
       if (vote.equals("Sparkle")) {
         sparkle = sparkle + 1;
       } else {
         dregraal = dregraal + 1;
       }
     } else {
       voter = ctxNode.parentNode;
       voterStatus = voter.getAttribute("status");
       if (voterStatus.equals("primary")) {
         if (vote.equals("Sparkle")) {
           sparkle = sparkle + 1;
         } else {
           dregraal = dregraal + 1;
         }
       }
     }
     return null;
   }

   function getResults(){
     return "Sparkle: "+sparkle+" Dregraal: "+dregraal;
   }
  </lxslt:script>
 </lxslt:component>
...
<xsl:template match="vote">
  <results:addVote enforced="yes"/>
</xsl:template>

</xsl:stylesheet>

The first parameter of an extension element's function represents the context of the request. We can get the actual context node, vote, using the getContextNode() method. From here, vote is just a simple DOM Node object, so we can get its value by getting the value of the first child, its text node.

From there, we're checking to see whether voting restrictions are being enforced. If they're not, we're simply updating totals, as before. If voting restrictions are being enforced, we'll need to check the voter's status.

Because the context node is just a DOM Node object, we can get its parent, voter, from the parentNode attribute of the object. (This is comparable to getParentNode() in Java.) The voter's status is represented by the status attribute, so again, we can use a traditional DOM method to get it. If the voter is the primary, we count the vote. If not, we do nothing.

Now when we run the transformation, the voting restrictions will be taken into account:

Sparkle: 1 Dregraal: 2

C++ and Visual Basic .NET

MSXML doesn't currently support extension elements.

PHP and Perl

Sablotron doesn't currently support extension elements.

External Classes

All this is well and good, but what if you don't want to do your extensions in JavaScript? Maybe you want to keep them separate and private. In that case, you'll want to use an external class to hold your functions.

An external class is a single class that holds all the functions that extension elements or functions in use may need to execute. For example, Listing 10.27 shows all of our functions converted to a single Java class, VoteSystem.

Listing 10.27 The VoteSystem Functions

import org.apache.xalan.extensions.XSLProcessorContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class VoteSystem {

  int sparkle = 0;
  int dregraal = 0;

  public String getResults(){
    return "Sparkle: "+sparkle+" Dregraal: "+dregraal;
  }

  public void addVote( XSLProcessorContext ctx, Element elem)
  {
    Node ctxNode = ctx.getContextNode();
    String vote = ctxNode.getFirstChild().getNodeValue();
    if (elem.getAttribute("enforced").equals("no")) {
       //Just add votes
       if (vote.equals("Sparkle")) {
         sparkle = sparkle + 1;
       } else {
         dregraal = dregraal + 1;
       }
     } else {
       Element voter = (Element)ctxNode.getParentNode();
       String voterStatus = voter.getAttribute("status");
       if (voterStatus.equals("primary")) {
         if (vote.equals("Sparkle")) {
           sparkle = sparkle + 1;
         } else {
           dregraal = dregraal + 1;
         }
       }
     }
   }
}

Note that these are straight conversions from JavaScript. With the exception of a few variable casting and typing issues, the class is identical to what we had. Now we need to tell the style sheet where to find the functions, as shown in Listing 10.28.

Listing 10.28 Using an External Class

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:lxslt="http://xml.apache.org/xslt"
        xmlns:results="http://www.example.com/results"
        extension-element-prefixes="results"
        version="1.0">


 <lxslt:component prefix="results" functions="getResults" elements="addVote">
   <lxslt:script lang="javaclass" src="VoteSystem"/>
 </lxslt:component>

<xsl:template match="/">

  <xsl:apply-templates select="votes/voter/vote"/>
  <xsl:value-of select="results:getResults()"/>

</xsl:template>

<xsl:template match="vote">
  <results:addVote enforced="yes"/>
</xsl:template>

</xsl:stylesheet>

In this case, the only thing that changes is where the processor looks for the functions.

PHP

There is currently no way to write XSL extensions in PHP.

Perl

Sablotron doesn't support writing XSL extensions in Perl, but the Perl wrapper for the Xalan project from the Apache group does provide such support. I've chosen not to use it for examples here for various reasons, but if you need support for Perl extension functions, it's your only option at present. You can find more information about Xalan at http://xml.apache.org/xalan-c, and about XML::Xalan, the Perl wrapper for Xalan, at http://search.cpan.org.

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