XML technologies / XML / Perl & XML / Programmer strategies / Converting XML to HTML with XSLT

(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)

If you have programmed for the web in Perl, in a sense you have already worked with XML: HTML is not far from XML’s well-formedness principles, at least in theory. In practice, HTML combines markup, embedded scripts, metadata and a dozen other things. This variety makes reliable results on modern websites difficult. Unfortunately, browsers’ excessive tolerance of malformed constructs and HTML programmers’ laziness encourage this development.

HTML is currently the web’s dominant language and will probably remain so for some time. But XML can already be used for websites by relying on the W3C standard XHTML.

XHTML comes in two variants. We prefer the less strict “transitional” style, a kind of transition to HTML. It generously overlooks familiar sins, such as using <font> tags instead of the recommended cascading stylesheets.

To avoid problems for users with older browsers and similar issues, you will quite likely have to convert your pages to HTML.

There are many ways to do this. The brute-force approach parses a document and outputs it through a CGI script. The following example reads a MonkeyML file naming my pet monkeys and outputs a standard web page. It uses Lincoln Stein’s unique CGI module for a little syntactic sugar.

#!/usr/bin/perl

use warnings;
use strict;
use CGI qw(:standard);
use XML::LibXML;

my $parser = XML::XPath;
my $doc = $parser->parse_file('monkeys.xml');

print header;
print start_html("Meine Hausaffen");
print h1("Meine Hausaffen");
print p("Zu Hause habe ich die folgenden Affen:");
print "<ul>\n";
foreach my $name_node ($doc->documentElement->findnodes("//mm:name")) {
    print "<li>" . $name_node->firstChild->getData ."</li>\n";
}

print end_html;

Another possibility is XSLT.

Here XSLT transforms one XML document into another. It fits well because the output HTML is often simply a presentation of information already in an XML document. Matt Sergeant’s AxKit is a very comprehensive application designed specifically for this purpose (http://www.axkit.org). This server framework lets you develop a website as XML files, which AxKit dynamically converts to HTML and sends to the browser.

Example: Apache::DocBook

Let us write a small module that reads DocBook files and converts them to HTML. Our goal is less ambitious than AxKit’s, but we borrow some ideas, including relying on mod_perl. This module adds a Perl interpreter to Apache and is the fastest way to generate HTML dynamically using Perl.

We use some of the main features of mod_perl, beginning with our own Perl module containing a subroutine named handler. This is a standard name prescribed by mod_perl. The function is called as a callback by mod_perl and receives an object simulating the HTTP request Apache received.

Warning! When developing with Perl and XML inside Apache, the server itself often causes frustration—more precisely, its compile-time options. The standard Apache distribution includes the C library Expat, integrated into Apache unless explicitly disabled. Unfortunately, this parser conflicts with the Expat parser used by XML::Parser. On Unix, for example, this can easily cause a segmentation fault or similar failures.
Apache developers intend to remove or at least hide this parser in future versions. For now, you may need to compile Apache without Expat before using XML::Parser. Set the configure option EXPAT to “no.”
It may be easier to use XML::LibXML or another parser from the XML::SAX family, since they do not rely on Expat.

We begin our movie “Dances with Modules” with a trip to Callback City:

package Apache::DocBook;   

use warnings;
use strict;

use Apache::Constants qw(:common);

use XML::LibXML;
use XML::LibXSLT;

our $xml_path; # Verzeichnis mit zu lesenden Dokumenten
our $base_path; # Verzeichnis für HTML-Ausgabe
our $xslt_file; # Pfad für DocBook-nach-HTML-Stylesheet
our $icon_dir; # Verzeichnis mit Icons für Indexseite

sub handler {
   my $r = shift; # Requestobjekt, von Apache übergeben
   # Konfiguration von Apache lesen
   $xml_path = $r->dir_config('doc_dir')
   or die "Variable doc_dir ist nicht gesetzt.\n";
   $base_path = $r->dir_config('html_dir')
   or die "Variable html_dir ist nicht gesetzt.\n";
   $icon_dir = $r->dir_config('icon_dir')
   or die "Variable icon_dir ist nicht gesetzt.\n";
   unless (-d $xml_path) {
   $r->log_reason("Das Verzeichnis $xml_path existiert nicht: $!", $r->filename);
   die;
   }
   my $filename = $r->filename;
   
   $filename =~ s/$base_path\/?//;
   # Pfad der zu erzeugenden Datei
      $filename .= $r->path_info;

      $xslt_file = $r->dir_config('xslt_file')
      or die "Variable xslt_file ist nicht gesetzt.\n";
     
   # Die folgenden Subroutinen besorgen die Ausgabe von HTML an den Client.
     
   # Soll ein Index ausgegeben werden?
      if ( (-d "$xml_path/$filename") or ($filename =~ /index.html?$/) ) {
   # Keine Indexseite vorhanden! Na und, machen wir eben eine.
      my ($dir) = $filename =~ /^(.*)(\/index.html?)?$/;
   # Der URI sollte einen abschließenden Slash (/) enthalten.
      if (not($2) and $r->uri !~ /\/$/) {
      $r->uri($r->uri . '/');
   }
      make_index_page($r, $dir);
      return $r->status;
   } else {
   # Nein, hier soll tatsächlich eine normale Seite ausgegeben werden.
      make_doc_page($r, $filename);
      return $r->status;
      }
      return $r->status;
}

The next subroutine performs the actual XSLT transformation. Its inputs are the original XML filename and the name of a file to receive the transformed HTML:

sub transform {    
    my ($filename, $html_filename) = @_;
      
    # Sicherstellen, daß das Zielverzeichnis existiert
    maybe_mkdir($filename);
      
    my $parser = XML::LibXML->new;
    my $xslt = XML::LibXSLT->new;
      
    # libxslt scheint einen Bug zu haben, der ein "include" anderer Dateien
    # nur dann funktionieren läßt, wenn man sich im betreffenden Verzeichnis
    # befindet.
    use Cwd; # Um das aktuelle Verzeichnis zu erhalten
    my $original_dir = cwd;
    my $xslt_dir = $xslt_file;
    $xslt_dir =~ s/^(.*)\/.*$/$1/;
    chdir($xslt_dir)
        or die "Kann nicht ins Verzeichnis $xslt_dir wechseln: $!";
    
    my $source = $parser->parse_file("$xml_path/$filename");
    my $style_doc = $parser->parse_file($xslt_file);
      
    my $stylesheet = $xslt->parse_stylesheet($style_doc);
      
    my $results = $stylesheet->transform($source);
      
    open (HTML_OUT, ">$base_path/$html_filename");
    print HTML_OUT $stylesheet->output_string($results);
    close (HTML_OUT);
      
    # Ins ursprüngliche Verzeichnis zurückkehren
    chdir($original_dir)
        or die "Kann nicht ins Verzeichnis $original_dir wechseln: $!";
}

Next come two subroutines for creating an index page. Unlike the detail pages generated from DocBook, this index is not an XSLT result. We fill a table with information retrieved from DocBook documents using XPath, then output it as HTML.

 sub make_index_page {   
      my ($r, $dir) = @_;
     
      # Wenn es kein entsprechendes Verzeichnis gibt, brechen wir ab.
     
      my $xml_dir = "$xml_path/$dir";
      unless (-r $xml_dir) {
      unless (-d $xml_dir) {
      # Das ist kein Verzeichnis!
   $r->status( NOT_FOUND );
   return;
   }
   # Das ist ein Verzeichnis, aber wir dürfen es nicht lesen.
   $r->status( FORBIDDEN );
   return;
   }
     
   # Lies die Modifikationszeiten des Verzeichnisses und der darin enthaltenen Dateien
      my $index_file = "$base_path/$dir/index.html";
     
      my $xml_mtime = (stat($xml_dir))[9];
      my $html_mtime = (stat($index_file))[9];
     
   # Wenn die Indexseite älter ist als das XML-Verzeichnis oder wenn sie nicht
   # existiert, erzeugen wir eine neue Indexseite.
   if ((not($html_mtime)) or ($html_mtime <= $xml_mtime)) {
      generate_index($xml_dir, "$base_path/$dir", $r->uri);
      $r->filename($index_file);
      send_page($r, $index_file);
      return;
   } else {
   # Die Indexseite ist immer noch aktuell. Der Apache-Server darf sie ausgeben.
   $r->filename($index_file);
   $r->path_info('');
   send_page($r, $index_file);
      return;
   }
   }
   
sub generate_index {
   my ($xml_dir, $html_dir, $base_dir) = @_;
  
   # Evtl. abschließendes / aus base_dir entfernen.
      $base_dir =~ s|/$||;
     
      my $index_file = "$html_dir/index.html";
     
      my $local_dir;
      if ($html_dir =~ /^$base_path\/*(.*)/) {
         $local_dir = $1;
      }

   # Falls erforderlich, Zielverzeichnis erstellen
   maybe_mkdir($local_dir);
   open (INDEX, ">$index_file")
   or die "Kann die Datei $index_file nicht erzeugen: $!";
   
   opendir(DIR, $xml_dir) or die "Kann das Verzeichnis $xml_dir nicht öffnen: $!";
   chdir($xml_dir) or die "Kann nicht in das Verzeichnis $xml_dir wechseln: $!";
   
   # Icondateien setzen
   my $doc_icon = "$icon_dir/generic.gif";
   my $dir_icon = "$icon_dir/folder.gif";
   
   # Erzeuge einen sprechenden Namen für $local_dir (möglicherweise einfach
   # den Verzeichnisnamen)
   my $local_dir_label = $local_dir || '/';
   
   # Start der Seite ausgeben
   print INDEX <<END;
   <html>
   <head><title>Inhaltsverzeichnis von $local_dir_label</title></head>
   <body>
   <h1>Inhaltsverzeichnis von $local_dir_label</h1>
   table width="100%">
   END
   
   # Pro Datei eine Zeile mit Link ausgeben
   
   while (my $file = readdir(DIR)) {
   # Ignoriere .sowieso-Dateien und Verzeichnisse
   if (-f $file && $file !~ /^\./) {
      # Parser erzeugen
      my $parser = XML::LibXML->new;
     
      # Datei lesen und überspringen, falls nicht wohlgeformt:
      my $doc;
      eval {$doc = $parser->parse_file($file);};
   if ($@) {
      warn "Die Datei $file scheint kein XML-Dokument zu sein.";
      warn $@;
      next;
      }
     
   my %info;               # Wird mit Informationen gefüllt
     
    Dokumenttyp bestimmen
   my $root = $doc->documentElement;
   my $root_type = $root->getName;
     
   # Information wird aus einem speziellen Infoknoten gelesen, der den Namen
   # $FOOinfo trägt.
   my ($info) = $root->findnodes("${root_type}info");
   if ($info) {
     
      # Gefunden, fülle %info damit.
   if (my ($abstract) = $info->findnodes('abstract')) {
      $info{abstract} = $abstract->string_value;
      } elsif ($root_type eq 'reference') {
     
   if ( ($abstract) =
      $root->findnodes('/reference/refentry/refnamediv/refpurpose') ) {
      $info{abstract} = $abstract->string_value;
     }
   }
   if (my ($date) = $info->findnodes('date')) {
      $info{date} = $date->string_value;
      }
   }
   if (my ($title) = $root->findnodes('title')) {

      $info{title} = $title->string_value;
   }

   # Für einige Informationen brauchen wir kein XML ...
   unless ($info{date}) {
   my $mtime = (stat($file))[9];
   $info{date} = localtime($mtime);
   }
   $info{title} ||= $file;
   
   # Das genügt. Wir können jetzt eine Zeile HTML ausgeben.
   print INDEX "<tr>\n";
   
   # Wir simulieren einen Dateinamen für einen Link -- foo.html
   my $html_file = $file;
   $html_file =~ s/^(.*)\..*$/$1.html/;
   print INDEX "<td>";
   print INDEX "<img src=\"$doc_icon\">" if $doc_icon;
   print INDEX "<a href=\"$base_dir/$html_file\">$info{title}</a></td> ";
   foreach (qw(abstract date)) {
      print INDEX "<td>$info{$_}</td> " if $info{$_};
   }
      print INDEX "\n</tr>\n";
   } elsif (-d $file) {
     
   # Eventuell Link auf ein Verzeichnis erzeugen
   # ... sofern das Verzeichnis nicht besser ignoriert wird.
   next if grep (/^$file$/, qw(RCS CVS .)) or ($file eq '..' and not $local_dir);
   print INDEX "<tr>\n<td>";
   print INDEX "<a href=\"$base_dir/$file\"><img src=\"$dir_icon\">" if $dir_icon;
   print INDEX "$file</a></td>\n</tr>\n";
   }
   }


   # Tabelle und Seite beenden
   print INDEX <<END;
 </table>
 </body>
 </html>
 END
   
 close(INDEX) or die "Konnte $index_file nicht schließen: $!";
 closedir(DIR) or die "Konnte $xml_dir nicht schließen: $!";
 }

The following subroutines build on these transformations and complete the HTML pages. Modification times of DocBook and HTML files are compared to implement a cache. HTML is regenerated only if older than DocBook; if no HTML file exists, a new one is always created.

 sub make_doc_page {    
     my ($r, $html_filename) = @_;
      
    # Generiere den Namen der Eingabedatei, indem die Endung durch .xml
    # ersetzt wird.
    my $xml_filename = $html_filename;
    $xml_filename =~ s/^(.*)(?:\..*)$/$1.xml/;
      
    # Falls es ein Problem beim Lesen der XML-Eingabedatei gibt, wird eine
    # Fehlermeldung ausgegeben.
    unless (-r "$xml_path/$xml_filename") {
        unless (-e "$xml_path/$xml_filename") {
        $r->status( NOT_FOUND );
        return;
    } else {
        # Existiert, aber keine Berechtigung zum Lesen
        $r->status( FORBIDDEN );
        return;
        }
    }
      
    # Lies die Modifikationszeiten der beiden Dateien zum Vergleich
    my $xml_mtime = (stat("$xml_path/$xml_filename"))[9];
    my $html_mtime = (stat("$base_path/$html_filename"))[9];
    # Eine HTML-Datei wird erzeugt, wenn sie noch nicht existiert oder wenn
    # die XML-Datei neueren Datums ist.
      
    if ((not($html_mtime)) or ($html_mtime <= $xml_mtime)) {
        transform($xml_filename, $html_filename);
        $r->filename("$base_path/$html_filename");
        $r->status( DECLINED );
        return;
    } else {
        # Treffer im Cache. Laß Apache die existierende Datei ausgeben.
        $r->status( DECLINED );
        }
    }
    
 sub send_page {
    my ($r, $html_filename) = @_;
    # Wenn die Zieldatei gerade eben erst erzeugt wird, können wir anschließend
    # nicht mit einem 'DECLINED' die Ausgabe an den Apache übergeben, da dieser
    # dann ein File-not-found melden würde.
    $r->status( OK );
    $r->send_http_header('text/html');
    open(HTML, "$html_filename")
        or die "Konnte Datei $base_path/$html_filename nicht lesen: $!";
    while (<HTML>) {
        $r->print($_);
    }
    close(HTML) or die "Konnte die Datei $html_filename nicht schließen: $!";
    return;
}

Finally, a function ensures all required directories exist. The HTML directory structure mirrors that of the original XML directory:

sub maybe_mkdir {    
    # Erzeuge zu einem gegebenen vollständigen Pfad alle noch nicht vorhandenen
    # Teilverzeichnisse
    my ($filename) = @_;
    my @path_parts = split(/\//, $filename);
    # Entferne eventuellen Dateinamen
    pop(@path_parts) if -f $filename;
    my $traversed_path = $base_path;
    foreach (@path_parts) {
        $traversed_path .= "/$_";
        unless (-d $traversed_path) {
            mkdir ($traversed_path)
              or die "Konnte das Verzeichnis $traversed_path nicht erzeugen: $!";
      }
    }
    return 1;
}

  

  

 

 

 

back to top