14.7. Transforming an XML Document with XSLT

Problem

You want to transform an XML document using an XSLT stylesheet.

Solution

Use the Xalan library. First, construct an instance of the XSTL engine xalanc::XalanTransformer. Next, construct two instances of xalanc::XSLTInputSource—one to represent the document to be transformed and the other to represent your stylesheet—and an instance of xalanc::XSLTResultTarget to represent the document to be generated by the transformation. Finally, call the XSLT engine’s transform() method, passing the two XSLTInputSources and the XSLTResultTarget as arguments.

For example, suppose you want to be able to view the list of circus animals from Example 14-1 with your web browser. An easy way to do this is with XSLT. Example 14-19 shows an XSLT stylesheet that takes an XML document like animals.xml as input and generates an HTML document containing a table with one data row per animal listing the animal’s name, species, date of birth, veterinarian, and trainer. Example 14-20 shows how to use the Xalan library to apply this stylesheet to the document animals.xml. The HTML generated by the program in Example 14-20 is shown in Example 14-21, reformatted for readability.

Example 14-19. Stylesheet for animals.xml

<?xml version="1.0" encoding="utf-8"?> <!-- Stylesheet for Feldman Family Circus Animals --> <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="/"> <html> <head> <title>Feldman ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.