Home > Articles

  • Print
  • + Share This
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
  • + Share This
  • 🔖 Save To Your Account