XML technologies / XML / Perl & XML / Programmer strategies / Subclasses

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

When writing Perl/XML modules, remember to look over—and stand on—the shoulders of giants: authors of general XML parsers and similar modules. This makes application-specific modules quick and easy to write, something we lazy authors appreciate.

You need not start with inheritance. The simplest approach creates a parser in the constructor, stores it and later uses it to process raw XML, like this:

package XML::MyThingy;    

use strict;
use warnings;
use XML::SomeSortOfParser;

sub new {
    # Der Konstruktor
    my $invocant = shift;
    my $self = {};
    if (ref($invocant)) {
    bless ($self, ref($invocant));
    } else {
    bless ($self, $invocant);
    }
      
    # Wir erzeugen einen XML-Parser...
    my $parser = XML::SomeSortOfParser->new
    or die "Oh nein, kein XML-Parser gefunden. Wie schade.";
      
    # ... und für die spätere Verwendung sichern wir ihn.
    $self->{xml} = $parser;
return $self;
}

sub parse_file {
  
    # Alles was wir tun, ist, den Aufruf des Benutzers an den Parser weiterzugeben.
    # (Zufällig hat dieser eine Methode namens parse_file ...)
    my $self = shift;
    my $result = $self->{xml}->parse_file;
      
    # Das folgende hängt vom Verhalten des XML::SomeSortOfParser-Objekts ab.
    # Nehmen wir an, es speichert das gelesene Dokument intern und liefert
    # einen Fehlercode. Wir lassen also den Parser im Schlüssel 'xml' stehen
    # und geben einfach den Fehlercode zurück.
    return $result;
}

Subclassing has advantages, however. It inherits basic methods, especially document parsing, without effort. Supporting variants such as parse_file, parse_string and so forth, this can save substantial work, especially in an application-specific helper module. With tree parsers, borrow and extend their data structures; small adjustments often suffice. Perl’s object orientation is invaluable here.

Subclass example: XML::ComicsML

For this example, reluctantly leave MonkeyML for ComicsML, a markup language for online comics. Many features and ideas come from RSS, including standardized information synchronization. A ComicsML helper should benefit anyone programming web comics.

Here we take a fully DOM approach and choose XML::LibXML because it nearly follows DOM and includes a fast parser. Our goal is a complete object-oriented interface for ComicsML documents and their main elements:

use XML::ComicsML;

# Lesen einer existierenden ComicsML-Datei
my $parser = XML::ComicsML::Parser->new;
my $comic = $parser->parsefile('my_comic.xml');

my $title = $comic->title;
print "Der Titel dieses Comics ist: $title\n";

my @strips = $comic->strips;
print "Er enthält ".scalar(@strips)." verschiedene Strips4.\n";

Enough talk; let us program:

package XML::ComicsML;

# Ein Hilfsmodul zum Parsen und Bearbeiten von ComicsML-Dokumenten.
use XML::LibXML;
use base qw(XML::LibXML);

# PARSEN

# Wir übernehmen die Ausgabe der verschiedenen Methoden von XML::LibXML
# und transferieren verschiedene Knoten in unsere eigenen Klassen, die
# entsprechende Subklassen sein müssen.

sub parse_file {    
    # Parsen wie üblich, Transfer des Root-Dokuments und Rückgabe.
    my $self = shift;
    my $doc = $self->SUPER::parse_file(@_);
    my $root = $doc->documentElement;
    return $self->rebless($root);
}

sub parse_string {
    # Parsen wie üblich, Transfer des Root-Dokuments und Rückgabe.
    my $self = shift;
    my $doc = $self->SUPER::parse_string(@_);
    my $root = $doc->documentElement;
    return $self->rebless($root);
}

We declared our package a subclass of XML::LibXML with the pragma use base and overrode two methods. Both call the corresponding method of XML::LibXML and transfer the resulting object into our own namespace by calling this internal method:

sub rebless {   
  
   # Erhält eine Instanz von XML::LibXML::Node (genauer gesagt einer Subklasse)
   # und übernimmt diese in eine der ComicsML-Klassen.
   my $self = shift;
   my ($node) = @_;
     
   # Hash interessanter Elemente (macht die Suche einfacher)
   my %interesting_elements = (comic=>1,
            person=>1,
            panel=>1,
            panel-desc=>1,
            line=>1,
            strip=>1,
           );
     
   # Wenn dies kein interessantes Element ist, dann tue nichts.
      my $name = $node->getName;
      return $node unless ( $node->isa('XML::LibXML::Element')
         and (exists($interesting_elements{$name})) );
  
   # Dies ist ein interessantes Element! Finde die zugehörige Klasse und mache das
   # Element zu einer Instanz dieser Klasse.
   my $class_name = $self->element2class($name);
   bless ($node, $class_name);
  return $node;
}

sub element2class {
   # Umwandlung eines XML-Elementnamens in einen passenden Klassennamen.
   my $self = shift;
   my ($class_name) = @_;
   $class_name = ucfirst($class_name);
   $class_name =~ s/-(.?)/uc($1)/e;
   $class_name = "XML::ComicsML::$class_name";
}

The method rebless receives an element node and checks its name against a hard-coded list of interesting names. If matched, the method element2class selects a class and makes the node its instance. Besides the egotistical pleasure of attaching our names to another’s work, we can add methods to these classes and transferred objects. We still need to define those classes and methods.

Mostly we do this by declaring a method AUTOLOAD in the class XML::ComicsML::Element, an abstract base for our real element classes. When an unknown method is called, Perl invokes this one automatically. It checks whether the name is an allowed element or attribute; if so, it treats the call as a getter or setter. If not, but the name is add_foo or remove_foo, it adds or removes a corresponding element of our classes:

package XML::ComicsML::Element;

# Abstrakte Basisklasse für alle Knotentypen von ComicsML.
use base qw(XML::LibXML::Element);
use vars qw($AUTOLOAD @elements @attributes);

sub AUTOLOAD {    
    my $self = shift;
    my $name = $AUTOLOAD;
    $name =~ s/^.*::(.*)$/$1/;
    my @elements = $self->elements;
    my @attributes = $self->attributes;
      
      # Ist ein Kindelement $name erlaubt?
    if (grep (/^$name$/, @elements)) {
      
    # Ja; ist ein zu setzender Wert angegeben?
    if (my $new_value = $_[0]) {
    # Wert wird gesetzt und überschreibt ein evtl. vorhandenes Element dieses Typs.
    my $new_node = XML::LibXML::Element->new($name);
    my $new_text = XML::LibXML::Text->new($new_value);
    $new_node->appendChild($new_text);
    my @kids = $new_node->childNodes;
    if (my ($existing_node) = $self->findnodes("./$name")) {
    $self->replaceChild($new_node, $existing_node);
    } else {
    $self->appendChild($new_node);
    }
  }
    
    # Gib den Inhalt des betreffenden Elements zurück.
    if (my ($existing_node) = $self->findnodes("./$name")) {
    return $existing_node->firstChild->getData;
    } else {
    return '';
  }

    # Nein, ein Kindelement $name ist nicht erlaubt,
    # aber vielleicht ein Attribut $name?
    } elsif (grep (/^$name$/, @attributes)) {
    # Ja; ist ein zu setzender Wert angegeben?
    if (my $new_value = $_[0]) {
    # Attributwert setzen
    $self->setAttribute($name, $new_value);
  }

    # Attributwert als Ergebnis liefern
    return $self->getAttribute($name) || '';
    
    # Nein, auch ein Attribut $name ist nicht erlaubt. Vielleicht soll ein neues
    # Element unserer eigenen Klasse hinzugefügt werden?
  } elsif ($name =~ /^add_(.*)/) {
    my $class_to_add = XML::ComicsML->element2class($1);
    my $object = $class_to_add->new;
    $self->appendChild($object);
    return $object;
    
    # ... oder eines entfernt werden?
  } elsif ($name =~ /^remove_(.*)/) {
    my ($kid) = @_;
    $self->removeChild($kid);
    return $kid;
  }

}

# Stub-Funktionen; standardmäßig sind weder Kindelemente noch Attribute erlaubt.

sub elements {
    return ();
}

sub attributes {
    return ();
}

package XML::ComicsML::Comic;
use base qw(XML::ComicsML::Element);

# Für ein Comic sind die Kindelemente 'version', 'title' usw. erlaubt.
# Durch AUTOLOAD kann man die Version mit $comic->version()
# lesen bzw. mit $comic->version(1) setzen.
sub elements {
return qw(version title icon description url);
}

sub new {
    my $class = shift;
    return $class->SUPER::new('comic');
}

sub strips {
    # Generiere eine Liste aller Strips, die in diesem Comic enthalten sind.
    my $self = shift;
    return map {XML::ComicsML->rebless($_)} $self->findnodes("./strip");
}

sub get_strip {
    # Finde den Strip mit der angegebenen 'id'.
    my $self = shift;
    my ($id) = @_;
    unless ($id) {
    warn "get_strip benötigt eine ID als Argument!";
    return;
    }
  
    my (@strips) = $self->findnodes("./strip[attribute::id='$id']");
    if (@strips > 1) {
    warn "Hoppla, es gibt mehr als einen Strip mit der ID $id?\n";
    }
    return XML::ComicsML->rebless($strips[0]);
}

Real ComicsML has many more element classes, for characters, strips and so on. We will return to this work and apply it to a concrete problem.

  

  

 

 

 

back to top