Transformations and SAX
Now that you've got an idea of how transformations work, it's time to throw a wrench into the works.
TrAX is pretty straightforward when we're dealing with objects such as files and DOM Nodes, but what happens when we throw SAX into the mix? With SAX, we have a stream of events, such as startElement and endDocument, so how can we incorporate this into a transformation?
It turns out that we have several options, each of which we'll discuss in the sections that follow:
Use TrAX as before, but with SAXSources and/or SAXResults.
Create a content handler that performs the transformation, and then parse the document as usual.
Chain transformations together, with or without XMLFilters.
Source and Style Sheet
In this section, we'll be taking a closer look at the results, so let's make sure we know what we're dealing with. As the source document, we'll use the votes from Chapter 5, "XML Streams: The Simple API for XML (SAX)," as shown in Listing 10.11.
Listing 10.11 The Source Data
<?xml version="1.0"?> <?xml-style sheet href="votes.xsl" type="text/xsl" ?> <votes totalVotes="5"> <voter personid="Emp1" status="primary"> <vote>Dregraal</vote> <extra:comments xmlns:extra="http://www.vanguardreport.com/extra"> I would like to request that the date of voting be changed. Any klybrtan youth would realize that it falls on the 334th of Meeps, the Holiest of days for Squreenks. It is totally unacceptable for us to vote then, since we have to spend the entire day in the positronic chamber of worship. </extra:comments> </voter> <voter personid="Emp2" status="symbiont"> <vote>Sparkle</vote> <extra:comments xmlns:extra="http://www.vanguardreport.com/extra"> Sfgrtng dwesvers melpy ypinee! </extra:comments> </voter> ... </votes>
The style sheet is straightforward; it changes the structure of the data to contain only the personid and vote, as shown in Listing 10.12.
Listing 10.12 The Style Sheet
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <finalVotes> <xsl:apply-templates /> </finalVotes> </xsl:template> <xsl:template match="votes/voter"> <vote> <person><xsl:value-of select="@personid"/></person> <candidate><xsl:value-of select="vote"/></candidate> </vote> </xsl:template> </xsl:stylesheet>
The results of this simple transformation are shown in Listing 10.13.
Listing 10.13 The Transformed Data
<?xml version="1.0" encoding="UTF-8"?> <finalVotes> <vote><person>Emp1</person><candidate>Dregraal</candidate></vote> <vote><person>Emp2</person><candidate>Sparkle</candidate></vote> <vote><person>Emp3</person><candidate>Dregraal</candidate></vote> <vote><person>Emp4</person><candidate>Dregraal</candidate></vote> <vote><person>Emp5</person><candidate>Sparkle</candidate></vote> </finalVotes>
SAX as Input
Let's start simple, with a SAXSource as input for a transformation. In Listing 10.14, we'll create a source of SAX events, and we'll use it as the input for the transformation.
Listing 10.14 Using a SAX Source in Java
import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.XMLReader; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class TransformFile extends Object { public static void main (String args[]) throws Exception { try { String XMLFileName = "votes.xml"; String OutputFileName = "finalvotes.xml"; String parserClass = "org.apache.crimson.parser.XMLReaderImpl"; XMLReader reader = XMLReaderFactory.createXMLReader(parserClass); SAXSource source = new SAXSource(reader, new InputSource(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); } catch (SAXException e) { System.out.println(e.getMessage()); } } }
To create SAX events, we need an XMLReader, so first we'll create that, just as we did when building an ordinary SAX application. We'll then use that XMLReader, along with a SAX InputSource for the original document, to create a SAXSource.
The rest of the application proceeds normally, as if we had specified a simple file as the input, but behind the scenes, the transformer sets itself as the ContentHandler for the XMLReader, then calls the parse() method. In this way, the events generated by parsing the document go to the Transformer, which transforms them into the new structure.
But what did we actually gain here, besides the necessity of specifying the classname for the XMLReader? Well, for one thing, because we're dealing with an XMLReader, we can set features on it. For example, we can set up the application so that in addition to transforming the document, the application validates it, as shown in Listing 10.15a.
Listing 10.15a Validating the Document
... String parserClass = "org.apache.crimson.parser.XMLReaderImpl"; XMLReader reader = XMLReaderFactory.createXMLReader(parserClass); String featureId = "http://xml.org/sax/features/validation"; reader.setFeature(featureId, true); SAXSource source = new SAXSource(reader, new InputSource(XMLFileName)); StreamResult result = new StreamResult(OutputFileName); ...
Now if we run the application, we'll see validation errors because we haven't specified a DTD or XML Schema.
C++ and Visual Basic .NET
The XSLT processor in these examples, MSXSL, has no means of using SAX events as direct input.
PHP
PHP has no way to use SAX events as direct input for an XSLT processor.
Perl
You can use SAX events to build a Sablotron DOM tree with the XML::Sablotron::SAXBuilder module, and then pass that DOM tree to XML::Sablotron for processing using addArgTree(). In effect, then, you can use SAX events as input for the XSLT processor, though somewhat indirectly. XML::Sablotron::SAXBuilder conforms to the Perl SAX 2 standard set by XML::SAX, so you should be able to use it with any source of Perl-standard SAX events. Here we use it with XML::SAX and XML::SAX::Expat.
One major drawback to using XML::Sablotron::SAXBuilder is that the source XML document cannot contain any elements outside of the default XML namespace; the processor will exit with an error if it encounters any such elements. To execute the remaining examples using XML::Sablotron, copy the votes.xml file to a new file called ne_votes.xml, and edit the <extra:comments> tags to remove the namespace.
This:
<extra:comments xmlns:extra="http://www.vanguardreport.com/extra"> ... </extra:comments>
becomes this:
<comments> ... </comments>
Use this file as the source document for the remaining examples in this chapter.
Listing 10.15b shows the transformation using the SAX stream representing the new document as the source.
Listing 10.15b Using a SAX Source in Perl
use XML::Sablotron; use XML::Sablotron::SAXBuilder; use XML::SAX; $XML::SAX::ParserPackage = 'XML::SAX::Expat'; my $xsl = new XML::Sablotron; my $sit = new XML::Sablotron::Situation; eval { my $builder = new XML::Sablotron::SAXBuilder; my $factory = XML::SAX::ParserFactory->new(); my $parser = $factory->parser( Handler => $builder ); my $doc = $parser->parse_uri('ne_votes.xml'); my $sheet = get_associated_stylesheet( $sit, $doc ); my $style = XML::Sablotron::DOM::parseStylesheet( $sit, $sheet ); $xsl->addArgTree( $sit, 'source', $doc ); $xsl->addArgTree( $sit, 'style', $style ); $xsl->process( $sit, 'arg:/style', 'arg:/source', 'arg:/result' ); my $result = $xsl->getResultArg('arg:/result'); print $result; }; ...
Sablotron is based on XML::Parser, which is a nonvalidating parser. If you need validation and transformation, look into using XML::LibXSLT. XML:LibXSLT requires XML::LibXML, and is based on the GNOME XSLT library; see http://xmlsoft.org for more information.
The Transformer as ContentHandler
In the previous example, we used a SAX stream as the input for the transformation. Now let's look at using SAX for the middle piece of the puzzle, the style sheet. Listing 10.16 shows the explicit creation of a Transformer as a ContentHandler (as opposed to the implicit creation in the previous example).
Listing 10.16 The Transformer as ContentHandler
import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.XMLReader; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; public class TransformFile extends Object { public static void main (String args[]) throws Exception { try { String XMLFileName = "votes.xml"; String OutputFileName = "finalvotes.xml"; StreamSource source = new StreamSource(XMLFileName); StreamResult result = new StreamResult(OutputFileName); TransformerFactory transFactory = TransformerFactory.newInstance(); Source style = transFactory.getAssociatedStylesheet(source, null, null, null); SAXTransformerFactory saxTransFactory = (SAXTransformerFactory)transFactory; TransformerHandler trans = saxTransFactory.newTransformerHandler(style); trans.setResult(result); String parserClass = "org.apache.crimson.parser.XMLReaderImpl"; XMLReader reader = XMLReaderFactory.createXMLReader(parserClass); reader.setContentHandler(trans); reader.parse(XMLFileName); } catch (SAXException e) { System.out.println(e.getMessage()); } } }
In this case, we create the result as usual, and we create the source object just so we can extract the style sheet information. Next, we cast the TransformerFactory to a SAXTransformerFactory, and use it to create a TransformerHandler. The TransformerHandler is similar to a Transformer, but will be used as the ContentHandler. The TransformerHandler is also where we'll determine the destination of the transformation using the setResult() method.
Finally, we create the XMLReader, set the TransformerHandler as the ContentHandler, and parse the file. The TransformerHandler transforms the data, sending it to the result.
SAX as a Result
Okay, we've looked at SAX in the first two positions; now we'll look at a transformation where a stream of SAX events is the result.
For the SAX stream to make any sense, we've got to send it to a ContentHandler. In this case, we'll create one that totals the votes and outputs the results. (We won't get as detailed as we did in Chapter 5; we'll just total the votes.) The code for the ContentHandler is shown in Listing 10.17.
Listing 10.17 The ContentHandler
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class DataProcessor extends DefaultHandler { public DataProcessor () { super(); } StringBuffer thisText = new StringBuffer(); int sTally = 0; int dTally = 0; public static void println(String arg) { System.out.println(arg); } public void outputResults(){ println("Sparkle: "+sTally+" Dregraal: "+dTally); } public void endDocument() { outputResults(); } public void startElement (String namespaceUri, String localName, String qualifiedName, Attributes attributes) { thisText.delete(0, thisText.length()); } public void endElement (String namespaceUri, String localName, String qualifiedName) throws SAXException { if (localName.equals("candidate")){ if (thisText.toString().equals("Sparkle")){ sTally = sTally + 1; } else if (thisText.toString().equals("Dregraal")){ dTally = dTally + 1; } } thisText.delete(0, thisText.length()); } public void characters (char[] ch, int start, int length) { thisText.append(ch, start, length); } }
There's nothing new here; this is simply a version of the DataProcessor class from Chapter 5.
Now we want to create a SAXResult that sends events to this ContentHandler, as shown in Listing 10.18a.
Listing 10.18a Using a SAXResult
import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; public class TransformFile extends Object { public static void main (String args[]) throws Exception { String XMLFileName = "votes.xml"; String OutputFileName = "finalvotes.xml"; StreamSource source = new StreamSource(XMLFileName); SAXResult result = new SAXResult(new DataProcessor()); TransformerFactory transFactory = TransformerFactory.newInstance(); Source style = transFactory.getAssociatedStylesheet(source, null, null, null); Transformer trans = transFactory.newTransformer(style); trans.transform(source, result); } }
In many ways, this is the simplest of the SAX-related transformations. It's a normal TrAX transformation, but the result is a SAXResult that sends a SAX stream to the ContentHandler with which it's created.
When you execute the transformation, the personid attribute and vote element are converted to the person and candidate elements, as expected. These elements are then forwarded to DataProcessor, which acts on them. The result is the output specified in the endDocument() method:
Sparkle: 2 Dregraal: 3
C++
In C++, you can cause SAX events to be generated by the IXSLProcessor object by assigning a class to the IXSLProcessor put_output property that implements the methods of the ISAXContentHandler interface. If you need to handle other events, you will need to implement the appropriate interface(s) and implement the methods for those interfaces in the same class. Additionally, you must implement either the IStream interface or the IPersistStream interface to support the output of the final transformation. Building the application this way enables you to handle the SAX events as usual, but to have the process initiated by a transformation.
This is difficult to do in vanilla C++. It is much easier to implement in either MFC or ATL, where the handling of the interfaces and vtables and so on is managed for you, but unfortunately, such an implementation is well beyond the scope of this book. If you're curious, Listing 10.18b shows the basic application skeleton. I leave it to you to implement the appropriate interfaces.
Listing 10.18b Transforming to a SAX Stream in C++
#include "stdafx.h" #include "MySAXContentHandler.h" int _tmain(int argc, _TCHAR* argv[]) { ::CoInitialize(NULL); try { HRESULT hr = S_OK; if(hr==S_OK) { //Create the pointers for the XML, XSL, Template and Processor CComPtr<MSXML2::IXMLDOMDocument> pXMLDoc; CComPtr<MSXML2::IXMLDOMDocument> pXSLTDoc; CComPtr<MSXML2::IXSLTemplate> pXSLTTemplate; CComPtr<MSXML2::IXSLProcessor> pXSLTProcessor; VARIANT_BOOL vSuccess; vSuccess = VARIANT_TRUE; //Load pointers MySAXContentHandler* pContent = new MySAXContentHandler(); hr = pXMLDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument)); hr = pXSLTDoc.CoCreateInstance( __uuidof(MSXML2::FreeThreadedDOMDocument)); hr = pXSLTTemplate.CoCreateInstance(__uuidof(MSXML2::XSLTemplate)); //Load the XML, XSL and then set the Template to the XSL hr = pXMLDoc->load(CComVariant("c:\\sales.xml"), &vSuccess); hr = pXSLTDoc->load(CComVariant("c:\\transform.xsl"), &vSuccess); hr = pXSLTTemplate->putref_stylesheet(pXSLTDoc); //Create and configure the processor hr = pXSLTTemplate->createProcessor(&pXSLTProcessor); hr = pXSLTProcessor->put_input(CComVariant(pXMLDoc)); hr = pXSLTProcessor->put_output(_variant_t(pContent, true)); //Begin the transformation hr = pXSLTProcessor->transform(&vSuccess); //This is where you would output the result that was provided by //IStream or IPersistStream interface that you implemented in the //MySAXContentHandler class that was registered as the in //the put_output method of the pXSLTProcessor object. ... //End output } } catch(...) // For catching standard exceptions. { printf("Caught the exception"); } ::CoUninitialize(); return 0; }
Make the following changes to the MySAXContentHandler.h file:
class MySAXContentHandler : public ISAXContentHandler { ... private: wchar_t wchText[1000]; int sTally, dTally; void MySAXContentHandler::outputResults(void); };
Finally, update the MySAXContentHandler.cpp file:
#include "stdafx.h" #include "MySAXContentHandler.h" ... HRESULT STDMETHODCALLTYPE MySAXContentHandler::startDocument() { wchText[0] = 0; sTally = 0; dTally = 0; return S_OK; } HRESULT STDMETHODCALLTYPE MySAXContentHandler::endDocument() { outputResults(); return S_OK; } ... HRESULT STDMETHODCALLTYPE MySAXContentHandler::startElement( /* [in] */ wchar_t __RPC_FAR *pwchNamespaceUri, /* [in] */ int cchNamespaceUri, /* [in] */ wchar_t __RPC_FAR *pwchLocalName, /* [in] */ int cchLocalName, /* [in] */ wchar_t __RPC_FAR *pwchQualifiedName, /* [in] */ int cchQualifiedName, /* [in] */ ISAXAttributes __RPC_FAR *pAttributes) { wchText[0] = 0; return S_OK; } HRESULT STDMETHODCALLTYPE MySAXContentHandler::endElement( /* [in] */ wchar_t __RPC_FAR *pwchNamespaceUri, /* [in] */ int cchNamespaceUri, /* [in] */ wchar_t __RPC_FAR *pwchLocalName, /* [in] */ int cchLocalName, /* [in] */ wchar_t __RPC_FAR *pwchQualifiedName, /* [in] */ int cchQualifiedName) { if (wcsncmp(L"candidate", pwchLocalName, cchLocalName) == 0) { if (wcsncmp(L"Sparkle", wchText, wcslen(wchText)) == 0) sTally++; else if (wcsncmp(L"Dregraal", wchText, wcslen(wchText)) == 0) dTally++; } else wchText[0] = 0; return S_OK; } HRESULT STDMETHODCALLTYPE MySAXContentHandler::characters( /* [in] */ wchar_t __RPC_FAR *pwchChars, /* [in] */ int cchChars) { wcsncat(&*wchText, pwchChars, cchChars); return S_OK; } ... void MySAXContentHandler::outputResults() { printf("Sparkle: %s Dregraal: %s\n", sTally, dTally); }
Visual Basic .NET
In Visual Basic .NET, you can cause SAX events to be generated by the IXSLProcessor object by assigning a class to the IXSLProcessor output property that implements the methods of the IVBSAXContentHandler interface. If you also need error handling, you can implement those methods in the same class. This allows you to handle the SAX events as usual but to have the process initiated by a transformation.
To demonstrate this, you can make the following changes to the project that we used in Chapter 5 when we implemented a SAX parser. In this project, change the button's Text property to Transform XML and its Name property to btnTransform. Add new Label and TextBox controls to the main form, and set the text box's Name property to txtXSLFileName. Change the existing text box's Name property to txtXMLFileName and modify the label controls as appropriate so that the main form resembles the form in Figure 10.3.
Figure 10.3 The main form for the SAX Transformation example.
You should make the changes to the main form shown in Listing 10.18b in the code view.
Listing 10.18c Transforming to a SAX Stream in Visual Basic .NET
... Private Sub btnTransform_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTransform.Click Dim ContentHandler As New MyContentHandler(Me) Dim XMLDoc As New MSXML2.DOMDocument40() Dim XSLTDoc As New MSXML2.FreeThreadedDOMDocument40() Dim XSLTTemplate As New MSXML2.XSLTemplate40() Dim XSLTProcessor As MSXML2.IXSLProcessor On Error GoTo ErrorSub XMLDoc.async = False XMLDoc.load(txtXMLFileName.Text) XSLTDoc.async = False XSLTDoc.load(txtXSLFileName.Text) XSLTTemplate.stylesheet = XSLTDoc XSLTProcessor = XSLTTemplate.createProcessor() XSLTProcessor.input = XMLDoc 'Assign ContentHandler to processor output to receive SAX events XSLTProcessor.output = ContentHandler 'Perform the transformation XSLTProcessor.transform() Exit Sub ...
The changes in Listing 10.18c should be made to the MyContentHandler.vb class file.
... Dim myForm As New SAXMainForm() Dim thisText As String Dim sTally As Integer = 0 Dim dTally As Integer = 0 ... Public Sub endDocument() Implements MSXML2.IVBSAXContentHandler.endDocument outputResults() End Sub Public Sub startElement(ByRef strNamespaceURI As String, ByRef strLocalName As String, ByRef strQName As String, ByVal oAttributes As MSXML2.IVBSAXAttributes) Implements MSXML2.IVBSAXContentHandler.startElement thisText = Nothing End Sub Public Sub endElement(ByRef strNamespaceURI As String, ByRef strLocalName As String, ByRef strQName As String) Implements MSXML2.IVBSAXContentHandler.endElement If strLocalName.Equals("candidate") Then If thisText.Equals("Sparkle") Then sTally = sTally + 1 ElseIf thisText.Equals("Dregraal") Then dTally = dTally + 1 End If End If thisText = Nothing End Sub ... Public Sub outputResults() myForm.OutputText="Sparkle: " & sTally & " Dregraal: " _ & dTally & vbCrLf End Sub
PHP
Use the xslt_set_sax_handlers() function to register functions that the XSLT processor can use as handlers for SAX events. One caveat is that if you define one handler in a group (document, element, and so on), you must define all the handlers in that group, or the transformation will fail. (You can see in Listing 10.18d that we've defined a start_document() handler that does nothing.)
A further caveat is that xslt_set_sax_handlers() doesn't support the object-oriented processing approach that you can use with the "normal" XML parser with xml_set_object(). Your XSLT SAX handlers must be global functions, and if you want to pass any data between them or get data back from them, you must use global variables, as shown in Listing 10.18d.
Listing 10.18d Transforming to a SAX Stream in PHP
<?php $styles = array(); $xh = xslt_create(); $xml = join('',file('votes.xml')); $xsl = get_associated_stylesheet($xml,'default'); $args = array ( '/_xml' => $xml ); $handlers = array ( 'document' => array ( 'start_document', 'end_document' ), 'element' => array ( 'start_element', 'end_element' ), 'character' => 'characters' ); $result = array ( 'text' => '', 'stally' => 0, 'dtally' => 0 ); xslt_set_sax_handlers($xh, $handlers); ... function output_results () { global $result; echo "Sparkle: {$result['stally']} Dregraal: {$result['dtally']}<br>\n"; } function start_document () { // NOP } function end_document () { output_results(); } function start_element ($parser, $name, $data) { global $result; $result['text'] = ''; } function end_element ($parser, $name) { global $result; if ($name == 'candidate') { switch ($result['text']) { case 'Sparkle': $result['stally']++; break; case 'Dregraal': $result['dtally']++; break; } $result['text'] = ''; } } function characters ($parser, $data) { global $result; $result['text'] .= $data; } ... ?>
Perl
The complement to XML::Sablotron::SAXBuilder is XML::SAXDriver::Sablotron, which hooks into XML::Sablotron's native near-SAX handler support to provide a source of Perl SAX 2 standard SAX events. The content handler used here is unchanged from the one we used in earlier chapters. Listing 10.18e demonstrates a transformation that creates a SAX stream, which is then handled by the content handler.
Listing 10.18e Transforming to a SAX Stream in Perl
package MyContentHandler; use base qw(XML::SAX::Base); sub output_results { my $self = shift; print "Sparkle: $self->{s_tally} Dregraal: $self->{d_tally}\n"; } sub start_document { my $self = shift; $self->{text} = ''; $self->{s_tally} = 0; $self->{d_tally} = 0; } sub end_document { my $self = shift; $self->output_results(); } sub start_element { my $self = shift; $self->{text} = ''; } sub end_element { my $self = shift; my $el = shift; if ( $el->{LocalName} eq 'candidate' ) { if ( $self->{text} =~ /Sparkle/ ) { $self->{s_tally}++; } elsif ( $self->{text} =~ /Dregraal/ ) { $self->{d_tally}++; } } } sub characters { my $self = shift; my $text = shift; $self->{text} .= $text->{Data}; } package main; use XML::SAXDriver::Sablotron; my $source = 'ne_votes.xml'; my $style = 'votes.xsl'; my $handler = MyContentHandler->new(); eval { my $xsl = new XML::SAXDriver::Sablotron( Stylesheet => $style, Handler => $handler ); $xsl->parse_uri($source); }; if ($@) { die "Error processing $source with $style: $@"; }
Chaining Transformations
In some situations, you'll want one transformation to feed into another. For example, we've narrowed the vote data down to just the person and the candidate. We might want to perform a second transformation to strip out everything but the candidate's name using a style sheet like the one in Listing 10.19.
Listing 10.19 The Second Style Sheet
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="finalVote/vote"> <xsl:value-of select="candidate"/><xsl:text> </xsl:text> </xsl:template> <xsl:template match="person"> </xsl:template> </xsl:stylesheet>
This style sheet works on the output of the first transformation.
To chain together these transformations, we want to set the result of the first transformation to be the source of the second transformation, as shown in Listing 10.20a.
Listing 10.20a Chaining Transformations in Java
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.TransformerFactory; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.XMLReader; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; public class TransformFile extends Object { public static void main (String args[]) throws Exception { try { String XMLFileName = "votes.xml"; String OutputFileName = "finalvotes.xml"; StreamSource source = new StreamSource(XMLFileName); StreamSource style1 = new StreamSource("votes.xsl"); StreamSource style2 = new StreamSource("votesOnly.xsl"); StreamResult result = new StreamResult(OutputFileName); TransformerFactory transFactory = TransformerFactory.newInstance(); SAXTransformerFactory saxTransFactory = (SAXTransformerFactory)transFactory; TransformerHandler trans1 = saxTransFactory.newTransformerHandler(style1); TransformerHandler trans2 = saxTransFactory.newTransformerHandler(style2); trans1.setResult(new SAXResult(trans2)); trans2.setResult(result); String parserClass = "org.apache.crimson.parser.XMLReaderImpl"; XMLReader reader = XMLReaderFactory.createXMLReader(parserClass); reader.setContentHandler(trans1); reader.parse(XMLFileName); } catch (SAXException e) { System.out.println(e.getMessage()); } } }
To keep things simple, we're specifying both style sheets directly and using them to create two different TransformerHandler objects. We set the result of trans1 to be a SAXResult that sends the output events to trans2. The output of trans2 is the original result file.
We're setting the ContentHandler for the reader to be trans1, so as the original file is parsed, its data is sent to trans1. The trans1 object performs the first transformation and sends the results to trans2, which performs the second transformation and sends its results to the finalvotes.xml file. The final result is simply the names of the candidates:
<?xml version="1.0" encoding="UTF-8"?> Dregraal Sparkle Dregraal Dregraal Sparkle
Perl
You can accomplish something like the transformation chaining possible with TrAX by using XML::Sablotron::SAXBuilder as the SAX handler for an XML::SAXDriver::Sablotron object. But since XML::Sablotron::SAXBuilder produces an XML::Sablotron::DOM object, not a stream of SAX events, you can't chain them together indefinitely. The last step in the chain must be an XML::Sablotron object to process the DOM document, as shown in Listing 10.20b.
Listing 10.20b Chaining Transformations in Perl
use XML::SAXDriver::Sablotron; use XML::Sablotron::SAXBuilder; my $source = 'ne_votes.xml'; my $sheet1 = 'votes.xsl'; my $sheet2 = 'votesOnly.xsl'; my $sit = new XML::Sablotron::Situation; my $xsl = new XML::Sablotron; my $builder = new XML::Sablotron::SAXBuilder; my $parser = new XML::SAXDriver::Sablotron( Stylesheet => $sheet1, Handler => $builder ); my $doc = $parser->parse_uri($source); my $style2 = XML::Sablotron::DOM::parseStylesheet( $sit, $sheet2 ); $xsl->addArgTree( $sit, 'source', $doc ); $xsl->addArgTree( $sit, 'style', $style2 ); $xsl->process( $sit, 'arg:/style', 'arg:/source', 'arg:/result' ); my $result = $xsl->getResultArg('arg:/result'); print $result;
SAX and XMLFilters
We can accomplish the same thing using XMLFilters, but we'll need to turn the order around a bit. Listing 10.21 shows the same transformation using XMLFilters.
Listing 10.21 Using XMLFilters in Java
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.TransformerFactory; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.XMLReader; import org.xml.sax.XMLFilter; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; public class TransformFile extends Object { public static void main (String args[]) throws Exception { try { String XMLFileName = "votes.xml"; String OutputFileName = "finalvotes.xml"; StreamSource source = new StreamSource(XMLFileName); StreamSource style1 = new StreamSource("votes.xsl"); StreamSource style2 = new StreamSource("votesOnly.xsl"); StreamResult result = new StreamResult(OutputFileName); TransformerFactory transFactory = TransformerFactory.newInstance(); SAXTransformerFactory saxTransFactory = (SAXTransformerFactory)transFactory; XMLFilter trans1 = saxTransFactory.newXMLFilter(style1); XMLFilter trans2 = saxTransFactory.newXMLFilter(style2); TransformerHandler output = saxTransFactory.newTransformerHandler(); output.setResult(result); String parserClass = "org.apache.crimson.parser.XMLReaderImpl"; XMLReader reader = XMLReaderFactory.createXMLReader(parserClass); trans1.setParent(reader); trans2.setParent(trans1); trans2.setContentHandler(output); trans2.parse(XMLFileName); } catch (SAXException e) { System.out.println(e.getMessage()); } } }
In this case, rather than creating TransformerHandler objects for the style sheets, we're creating XMLFilters using the SAXTransformerFactory. These XMLFilters include the instructions for carrying out each transformation as the filter gets its turn with the data.
We do need one TransformerHandler to act as the main ContentHandler, however, so we'll create one without a style sheetso it will pass the data through unchangedand set its result to be the output file.
As before, we set the parent for each filter, set the ContentHandler for the last filter, and use it to actually parse the document.
In this case, that means we ask trans2 to parse the file. It passes the request to its parent, trans1, which sends the request to its parent, reader. The reader object parses the file and sends its events to trans1, which acts on them and sends them to trans2, which acts on them and sends the results to its ContentHandler, output.