Home > Articles

This chapter is from the book

This chapter is from the book

Transforming Data

Let's start by taking a look at the specifics of putting together an application that simply uses a style sheet to transform a source document into a particular result document. In this case, we're using the term document loosely.

Sources

One of the advantages of TrAX is that it's designed to be able to handle XML from a variety of sources. Data may come from a file on the system or in a remote location, or it may come from an in-memory object, such as a DOM Node. It could even be a stream of data, in the sense of a character stream or a SAX stream.

All of these cases are handled by implementations of the Source interface. Listing 10.1a shows the StreamSource used to designate a file on the local system.

Listing 10.1a Creating the Source in Java

import javax.xml.transform.stream.StreamSource;

public class TransformFile extends Object {
  public static void main (String args[]) throws Exception
  {
   String XMLFileName = "events.xml";
   StreamSource source = new StreamSource(XMLFileName);
  }
}

In this case, we created the StreamSource with the system identifier for the file, but we can also create it with a File object, or with the output from a bytestream or character reader.

We could have used a DOMSource with a DOM Node object as the argument, or a SAXSource with an InputSource and potentially an XMLReader as arguments. We'll see how to do this in detail in the "Transformations and SAX" section.

C++

In C++, preparing for the transformation involves loading the XML file into a DOMDocument object. This is the same procedure as you would use when working with an XML using DOM normally. Listing 10.1b gets the document ready to work with.

Listing 10.1b Creating the Source in C++

#include "stdafx.h"
#import "C:\windows\system32\msxml2.dll"
using namespace MSXML2;

int _tmain(int argc, _TCHAR* argv[])
{
  ::CoInitialize(NULL);
  try
  {
    CComPtr<MSXML2::IXMLDOMDocument> pXMLDoc;
    pXMLDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument));
    pXMLDoc->load("events.xml");
  }
  catch(...)
  {
    wprintf(L"Caught the exception");
  }
  ::CoUninitialize();
  return 0;
}

Visual Basic .NET

In Visual Basic .NET, preparing for the transformation involves loading the XML file into a DOMDocument40 object, just as you would when working with DOM under other circumstances, as shown in Listing 10.1c.

Listing 10.1c Creating the Source in Visual Basic .NET

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
 System.EventArgs) Handles Button1.Click
    Dim XMLDoc As New MSXML2.DOMDocument40()
    XMLDoc.async = False
    XMLDoc.load("events.xml")
  End Sub

PHP

PHP merely requires the filename, so the basic code is simple, as shown in Listing 10.1d.

Listing 10.1d Creating the Source in PHP

<?php
 $xml = 'source.xml';
?>

Perl

Like PHP, Perl requires just the name, but we also have to import the Sablotron package, as shown in Listing 10.1e.

Listing 10.1e Creating the Source in Visual Basic .NET

use XML::Sablotron;

my $source = 'source.xml';

Results

Transformation results can also take multiple forms similar to those for transformation sources. In this case, we're referring to implementations of the Result interface. Listing 10.2a shows the most common form.

Listing 10.2a Creating the Result in Java

import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;

public class TransformFile extends Object {
  public static void main (String args[]) throws Exception
  {
   String XMLFileName = "events.xml";
   String OutputFileName = "transform.html";

   StreamSource source = new StreamSource(XMLFileName);
   StreamResult result = new StreamResult(OutputFileName);
  }
}

As with the StreamSource, we could have created the StreamResult in a variety of ways. Here we provide a relative URL as the system ID for a file. We could also provide a File object, or a Writer or OutputStream.

Like the Source interface, the Result interface has a DOMResult implementation that takes a Node as its argument, and a SAXResult implementation that takes a ContentHandler as its argument. Again, we'll see the SAXResult in detail in a later section.

C++

The result stream for MSXML can be one of two types. The first occurs when you use the transformNode() method. This creates a BSTR that contains the text that is the output of the transformation. The other output is as a DOMDocument object and is generated by the transformNodeToObject() method. We'll use the transformNode() method in this example, so Listing 10.2b simply creates a new variable to hold the result.

Listing 10.2b Creating the Result in C++

...
    CComPtr<MSXML2::IXMLDOMDocument> pXMLDoc;
    _bstr_t bstrXMLStr;
    pXMLDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument));
...

Visual Basic .NET

Similarly, in Visual Basic .NET, we'll simply create a variable to hold the result string, as shown in Listing 10.2c.

Listing 10.2c Creating the Result in Visual Basic .NET

...
    Dim XSLTDoc As New MSXML2.DOMDocument40()
    Dim myString As String

    'Load XMLDoc
    XMLDoc.async = False
    XMLDoc.load("events.xml")
...

PHP and Perl

PHP and Perl simply need a string for the resulting filename, as you'll see when we perform the transformation.

The TransformerFactory

Before we can create the actual Transformer object, we'll need a TransformerFactory. Listing 10.3 shows the creation of a TransformerFactory object that will create Transformers from the standard classes, whatever they happen to be for this particular implementation.

Listing 10.3 Creating the TransformerFactory

import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerFactory;

public class TransformFile extends Object {
  public static void main (String args[]) throws Exception
  {
   String XMLFileName = "events.xml";
   String OutputFileName = "transform.html";

   StreamSource source = new StreamSource(XMLFileName);
   StreamResult result = new StreamResult(OutputFileName);

   TransformerFactory transFactory = TransformerFactory.newInstance();
  }
}

It would seem that the next logical step would be to create the Transformer, but there's one task we need to accomplish first.

Plugging In Another Transformation Engine

The advantage of this architecture is that it allows you to choose a different implementation of the transformation engine, if that's what you want. For example, we could substitute the SAXON transformation for the reference implementation:

...
System.setProperty("javax.xml.parsers.TransformerFactory",
      "com.icl.saxon.om.TransformerFactoryImpl");
TransformerFactory transFactory = TransformerFactory.newInstance();
...

Determining the Style Sheet

The Transformer object is based on a particular style sheet, so before we can create the Transformer we need to determine the style sheet.

As far as TrAX is concerned, a style sheet is just another Source implementation, so it can be a file, a DOM Node, or a stream, just as the source itself can be any of these. In most cases, the style sheet will be a file, as shown in Listing 10.4.

Listing 10.4 Specifying a Style Sheet in Java

import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerFactory;

public class TransformFile extends Object {
  public static void main (String args[]) throws Exception
  {
   String XMLFileName = "events.xml";
   String XSLFileName = "style.xml";
   String OutputFileName = "transform.html";

   StreamSource source = new StreamSource(XMLFileName);
   StreamSource style = new StreamSource(XSLFileName);
   StreamResult result = new StreamResult(OutputFileName);

   TransformerFactory transFactory = TransformerFactory.newInstance();
  }
}

If it's this simple, why didn't we just specify the style sheet when we specified the source? It just so happens that we have another, much more powerful option for determining the style sheet. Rather than simply specifying it within the application, we can instruct the application to read the style sheet processing instruction in the document to determine the appropriate style sheet. For example, Listing 10.5 shows the XML document with two possible style sheets specified.

Listing 10.5 Specifying the Style Sheet within an XML document

<?xml version="1.0"?>
<?xml-style sheet href="events.xsl" type="text/xsl" ?>
<?xml-style sheet href="events_print.xsl" type="text/xsl" media="cellphone" ?>
<content>
<events>
  <eventitem eventid="A335">
...

The TransformerFactory object can read these processing instructions, as shown in Listing 10.6a.

Listing 10.6a Determining the Style Sheet

import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Source;

public class TransformFile extends Object {
  public static void main (String args[]) throws Exception
  {
   String XMLFileName = "events.xml";
   String OutputFileName = "transform.html";

   StreamSource source = new StreamSource(XMLFileName);
   StreamResult result = new StreamResult(OutputFileName);

   TransformerFactory transFactory = TransformerFactory.newInstance();
   Source style = transFactory.getAssociatedStylesheet(source,
                             null, null, null);
  }
}

The getAssociatedStylesheet() method allows you to choose a style sheet based on the media, title, and charset attributes in the processing instruction (in that order). For example, to choose the cellphone style sheet, you would use the following instruction:

Source style = transFactory.getAssociatedStylesheet(source, "cellphone",
                                null, null);

Once we have the style sheet Source, we're ready to create the Transformer.

C++

As with Java, the style sheet in C++ is a DOMDocument object that we load into the application just as we created the original XML document. Listing 10.6b shows the creation of the style sheet document.

Listing 10.6b Specifying a Style Sheet in C++

...
    CComPtr<MSXML2::IXMLDOMDocument> pXMLDoc;
    CComPtr<MSXML2::IXMLDOMDocument> pXSLTDoc;
    _bstr_t bstrXMLStr;

    pXMLDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument));
    pXSLTDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument));

    pXMLDoc->load("events.xml");
    pXSLTDoc->load("style.xsl");
...

Visual Basic .NET

In Visual Basic .NET, we also have to load the style sheet as a DOMDocument40 object, as shown in Listing 10.6c.

Listing 10.6c Specifying a Style Sheet in Visual Basic .NET

...
    Dim XMLDoc As New MSXML2.DOMDocument40()
    Dim XSLTDoc As New MSXML2.DOMDocument40()
    Dim myString As String

    'Load XMLDoc
    XMLDoc.async = False
    XMLDoc.load("events.xml")

    'Load XSLTDoc
    XSLTDoc.async = False
    XSLTDoc.load("style.xsl")
...

PHP

PHP has no equivalent to the built-in getAssociatedStyleSheet() function, but fortunately it's not hard to replicate. We've chosen to be "correct" and parse the source XML with an XML parser; if you want a faster but sloppier method, you can just use regular expressions to do the whole job. Listing 10.6d shows the function that parses the document and retrieves the style sheet information.

Listing 10.6d Parsing the Document and Retrieving the Style Sheet

<?php

 $styles = array();

 $xh = xslt_create();
 $xml = join('',file('events.xml'));
 $xsl = get_associated_stylesheet($xml,'cellphone');

 $args = array ( '/_xml' => $xml );

...

 function get_associated_stylesheet ($xml, $media="default")
 {
   global $styles;

   if (preg_match("/^(.*?)<[^?]/s", $xml, $matches)) {
     $xml = $matches[1];
   }

   $xp = xml_parser_create();
   xml_set_processing_instruction_handler($xp,'get_style');

   if (xml_parse($xp,$xml)) {

     if (isset($styles[$media])) {
       xml_parser_free($xp);
       return $styles[$media];
     }

     xml_parser_free($xp);
     die("No style sheet for media '$media' found");

   } else {

     xml_parser_free($xp);
     die("Error getting associated style sheet: " .
       xml_error_string($xp));

   }
 }

 function get_style ($parser, $target, $data)
 {
   global $styles;

   $matches = array();
   $media  = 'default';
   if ($target == 'xml-style') {
     if (preg_match('/media="([^"]+)"/',$data,$matches))
       $media = $matches[1];

     if (preg_match('/href="([^"]+)"/',$data,$matches))
       $styles[$media] = $matches[1];
   }
 }
?>

Perl

Using XML::Sablotron::DOM, you can pre-parse the source document to find the desired style sheet, without wasting a parse: You can pass the pre-parsed DOM structure to the XSLT processor, so the source document doesn't have to be parsed twice. You can also use this functionality to implement something like the templates provided by TrAX, which we'll discuss in the section titled "Templates and Parameters." You can pre-parse a style sheet and apply it to many source documents without reparsing it, or pre-parse a source document and transform it with many style sheets, without re-parsing the source document. (See Listing 10.10b in the section titled "Transforming Multiple Files" for an example.)

In Listing 10.6e, once we've parsed the source document into a DOM object, we use an XPATH query to find all the XML-style processing instructions and extract the style sheet name and media type for each.

Listing 10.6e Specifying a Style Sheet in Perl

use XML::Sablotron;
use XML::Sablotron::DOM;

my $source = 'events.xml';
my $xsl  = new XML::Sablotron;

my $sit = new XML::Sablotron::Situation;

my ( $media, $doc, $sheet, $style );
eval {
  $media = 'cellphone';
  $doc  = XML::Sablotron::DOM::parse( $sit, $source );
  $sheet = get_associated_stylesheet( $sit, $doc, $media );
  $style = XML::Sablotron::DOM::parseStylesheet( $sit, $sheet );
};

if ($@) {
  die "Error loading stylesheet for media type '$media': $@\n";
}
eval {

  $xsl->addArgTree( $sit, 'source', $doc );
  $xsl->addArgTree( $sit, 'sheet', $style );
  $xsl->process( $sit, 'arg:/sheet', 'arg:/source', 'arg:/result' );
  my $result = $xsl->getResultArg('arg:/result');
  print $result;
};

if ($@) {
  die "Error processing $source with $style: $@";
}

sub get_associated_stylesheet {
  my ( $sit, $doc, $media ) = @_;

  $media ||= 'default';

  my $doc_style_el =
   $doc->xql( "/processing-instruction('xml-style')", $sit );
  my %styles;

  foreach my $ds (@$doc_style_el) {
    my $data = $ds->getNodeValue($sit);
    my $mt  = 'default';

    if ( $data =~ /media="([^"]+)"/ ) {
      $mt = $1;
    }

    if ( $data =~ /href="([^"]+)"/ ) {
      $styles{$mt} = $1;
    }
  }

  die "No style sheet found for '$media'\n"
   unless $styles{$media};

  return $styles{$media};
}

Creating the Transformer and Transforming the Data

We've created the TransformerFactory object, we've determined the style sheet, and now we're ready to create the Transformer.

When we create the Transformer from the TransformerFactory, we feed it a style sheet that provides the instructions for all transformations it subsequently performs. We can create it without a style sheet, in which case it will perform an "identity transformation," essentially passing the information on unchanged. This ability can be useful in situations where we simply want to serialize XML data, sending it to a file or to an output stream such as a Web page.

In Listing 10.7a, we'll create the Transformer with the style sheet specified on the XML document, and then use it to actually perform the transformation.

Listing 10.7a Transforming the Source in Java

...
import javax.xml.transform.Transformer;

public class TransformFile extends Object {
  public static void main (String args[]) throws Exception
  {
   String XMLFileName = "events.xml";
   String OutputFileName = "transform.html";

   StreamSource source = new StreamSource(XMLFileName);
   StreamResult result = new StreamResult(OutputFileName);

   TransformerFactory transFactory = TransformerFactory.newInstance();
   Source style=transFactory.getAssociatedStylesheet(source, null, null, null);

   Transformer trans = transFactory.newTransformer(style);
   trans.transform(source, result);
  }
}

The Transformer object transforms the source (the list of events) into the result (an HTML file, in this case) using the instructions in the style sheet specified by the document. In this case, the result is a simple HTML page, as shown in Figure 10.1.

Figure 10.1Figure 10.1 A transformation can create a traditional HTML file to be opened in the browser, among other things.

C++

In C++, to begin the transformation of the XML document, we only need to make a call to the transformNode() or transformNodeToObject() method, as shown in Listing 10.7b.

Listing 10.7b Transforming the Source in C++

...
    CComPtr<MSXML2::IXMLDOMDocument> pXMLDoc;
    CComPtr<MSXML2::IXMLDOMDocument> pXSLTDoc;
    _bstr_t bstrXMLStr;

    pXMLDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument));
    pXSLTDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument));

    pXMLDoc->load("events.xml");
    pXSLTDoc->load("style.xsl");

    // This call will produce a string for output
    bstrXMLStr = pXMLDoc->transformNode(pXSLTDoc);
  }
...

Visual Basic .NET

In Visual Basic .NET, to begin the transformation of the XML document, we simply need to make a call to either the transformNode() method or the transformNodeToObject() method, as shown in Listing 10.7c.

Listing 10.7c Transforming the Source in Visual Basic .NET

...
    Dim XMLDoc As New MSXML2.DOMDocument40()
    Dim XSLTDoc As New MSXML2.DOMDocument40()
    Dim myString As String

    'Load XMLDoc
    XMLDoc.async = False
    XMLDoc.load("events.xml")

    'Load XSLTDoc
    XSLTDoc.async = False
    XSLTDoc.load("style.xsl")

    'Do the transformation
    myString = XMLDoc.transformNode(XSLTDoc)
  End Sub

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