XML technologies / XML / Perl & XML / RSS, SOAP and other XML applications / XML::RSS

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

By a helper module we essentially mean an XML processor like the many added to our toolkit in previous sections. The difference is its clear focus on one XML application, absent from general-purpose XML processors. In a sense, even XML::Parser and similar tools are helper modules: they free us from developing new functions for every piece of XML to read and write files using Perl’s file I/O and regular expressions. The same applies to XML::Writer and similar modules, which take XML work far beyond simple print statements.

The following XML modules, however, are clearly specialized. Using one in a program makes sense only if you have chosen XML not generally, but for a clearly defined area. You can then use, and write, modules shielding you from raw XML and offering interfaces where XML itself is often no longer apparent.

As an example, consider XML::RSS, a nice little application by Jonathan Eisenzopf.

Introduction to RSS

RSS (Rich Site Summary or Really Simple Syndication, depending on whom you ask) was one of the first XML applications to become popular through the Web. Originally, RSS mainly let website administrators provide metadata: content summaries, news, a logo and similar information. Designing such a format is easy; RSS’s crucial contribution was standardization. What an application does with the file is its own concern: email notifications or a summary on a dynamic HTML page, for instance. RSS aggregators visit several sites, read their RSS documents and combine them into new RSS documents.

Popular aggregators include Netscape’s configurable my.netscape.com (the birthplace of an early RSS version) and Dave Winer’s "http://www.scripting.com" (whose aggregator is simply a frontend for "http://aggregator.userland.com/register" ). These aggregators collect results in new RSS, letting one file provide information from many sources. Websites systematically collecting links and information often use aggregators to obtain and redistribute information about RSS-enabled sites. O’Reilly Network’s Meerkat server is a good example ("http://meerkat.oreillynet.com").

Using XML::RSS

The module XML::RSS helps both read existing RSS documents and create your own. Naturally, you can combine these operations: read, modify and write a document back. Its simple, well-documented object model maps RSS documents into memory, resembling the tree-processing modules we already know. Think of this XML helper as a clever wrapper around a more general tool.

The following examples use a weblog, a kind of diary: a frequently updated web file with personal information, experiences or opinions. RSS suits weblogs particularly well, especially for summarizing recent entries in a derived RSS document.

Here is a weblog example, admittedly near the lower limit of RSS’s possibilities, but intended to remain short. In a browser it might look like this:

18. Oktober 2002, 19:07:06

Habe heute den Laboraffen 45-X gefragt, wie er sich nach seinem jüngsten Sieg im Schach gegen Dr. Tscharotschkin fühlt. Als Antwort biß er mir ins Knie. (Der Affe, nicht Dr. Tscharotschkin.) Ich habe den Eindruck, daß dies ein wesentlicher Durchbruch in unserer Kommunikation sein könnte. Davon abgesehen könnte es eine ziemliche Schwellung geben, was die Freude etwas trübt.

27. Oktober 2002, 22:56:11

Nebenbei bemerkt, Dr. Berkemers Forschungen über einen Vergleich zwischen grünen und purpurroten Affen in Bezug auf die trans-soziopolitische Wirkung der Farbe scheinen keine rechten Fortschritte zu machen, zumindest hört man seit einigen Wochen nichts Neues. Heute hat er erfahren, daß sein Assistent farbenblind ist, was er in den Bewerbungsunterlagen zu erwähnen vergaß. Oh, Mann!

Here is the same document wrapped in RSS v1.0:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
    xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
    >
    <channel rdf:about="http://www.jmac.org/linklog/">
        <title>Thomas T’s Tagebuch</title>
        <link>http://www.jmac.org/linklog/</link>
        <description>Das Online-FOnline-Forschungsjournalorschungsjournal von Dr. Thomas Thaler</
            description>
            <dc:language>de-DE</dc:language>
            <dc:rights>Copright 2002 Dr. Thomas Thaler</dc:rights>
            <dc:date>2002-10-27 23:59:15 MESZ</dc:date>
            <dc:publisher>tthaler@jmac.org</dc:publisher>
            <dc:creator>tthaler@jmac.org</dc:creator>
            <dc:subject>tthaler</dc:subject>
            <syn:updatePeriod>daily</syn:updatePeriod>
            <syn:updateFrequency>1</syn:updateFrequency>
            <syn:updateBase>2002-03-03 00:00:00 MESZ</syn:updateBase>
            <items>
                <rdf:Seq>
                    <rdf:li rdf:resource="http://www.jmac.org/linklog?2002-10-27#22:56:11" />
                    <rdf:li rdf:resource="http://www.jmac.org/linklog?2002-10-18#19:07:06" />
                </rdf:Seq>
            </items>
    </channel>
    <item rdf:about="http://www.jmac.org/linklog?2002-10-27#22:56:11">
        <title>27. Oktober 2002, 22:56:11</title>
        <link>http://www.jmac.org/linklog?2002-10-27#22:56:11</link>
        <description>
            Habe heute den Laboraffen 45-X gefragt, wie er sich nach seinem jüngsten Sieg
            im Schach gegen Dr. Tscharotschkin fühlt. Als Antwort biß er mir ins Knie. (Der
            Affe, nicht Dr. Tscharotschkin.) Ich habe den Eindruck, daß dies ein wesentlicher
            Durchbruch in unserer Kommunikation sein könnte. Davon abgesehen könnte es eine
            ziemliche Schwellung geben, was die Freude etwas trübt.
        </description>
    </item>
    <item rdf:about="http://www.jmac.org/linklog?2002-10-18#19:07:06">
        <title>18. Oktober 2002, 19:07:06</title>
        <link>http://www.jmac.org/linklog?2002-10-18#19:07:06</link>
        <description>
            Nebenbei bemerkt, Dr. Berkemers Forschungen über einen Vergleich zwischen grünen
            und purpurroten Affen in Bezug auf die trans-soziopolitische Wirkung der Farbe
            scheinen keine rechten Fortschritte zu machen, zumindest hört man seit einigen
            Wochen nichts Neues. Heute hat er erfahren, daß sein Assistent farbenblind ist,
            was er in den Bewerbungsunterlagen zu erwähnen vergaß. Oh, Mann!
        </description>
    </item>
</rdf:RDF>

Notice that RSS 1.0 uses various namespaces to provide metadata about the content that follows.

We specify the RSS version carefully because versions 0.9 and 0.91 had a markedly different structure. The older structure was simpler, with neither namespaces nor RDF-wrapped metadata. Instead, it used a simple list of <item> elements inside an <rss> element. Many users still prefer older versions for this reason. Well-behaved RSS software reads and writes all these versions. XML::RSS is such software, and can also convert between the two formats.

If you wish, enter these namespace URIs in your browser: they actually lead to documentation. “dc” stands for “Dublin Core”, a standardized set of elements describing a document’s source. “syn”, by contrast, stands for synchronization: a handful of elements describing how long a document stays current and when it should be refreshed. Finally, the document itself is wrapped in RDF.

Parsing

Reading an existing document with XML::RSS should feel familiar. It resembles our earlier work and is quite simple:

use XML::RSS;

# Dateinamen von der Kommandozeile lesen    
my @rss_docs = @ARGV;

# Wir nehmen an, die Dateien stehen alle auf der Festplatte...
foreach my $rss_doc (@rss_docs) { 
  
    # Ein neues RSS-Objekt erzeugen, um das zu lesende Dokument zu repräsentieren
    my $rss = XML::RSS->new;
      
    # Und jetzt lassen wir’s lesen
    $rss->parsefile($rss_doc);
      
    # Das wär’s schon. Hier kann jeder machen, was er will.
}

Inheriting from XML::Parser

If the method parsefile seemed familiar, there is a good reason: it is inherited from our old grandfather XML::Parser.

XML::RSS exploits the extensibility of XML::Parser by adding it to its @ISA array when loaded.

If you know object-oriented Perl, it will not surprise you that XML:RSS defines its own methods but otherwise does little beyond calling SUPER::new. Initialization of XML::Parser therefore works as before. Examine some module source, specifically the constructor new used in the example above:

sub new {    
    my $class = shift;
    my $self = $class->SUPER::new(Namespaces => 1,
    NoExpand => 1,
    ParseParamEnt => 0,
    Handlers => { Char => \&handle_char,
    XMLDecl => \&handle_dec,
    Start => \&handle_start } );
    bless ($self,$class);
    $self->_initialize(@_);
    return $self;
}

Notice how the module calls its superclass’s new method with very specific arguments. These are ordinary, well-documented options from the public interface of XML::Parser. The subclass XML::RSS prevents users from choosing these parameters themselves because it has precise requirements: here, a namespace-aware parser object without parameter entity resolution or parsing. Above all, the subclass must install its own handlers.

Calling SUPER::new yields an instance of the class XML::Parser, which the subclass carefully hides from users—otherwise, what would the abstraction achieve? It therefore calls bless again, turning $self into an instance of its own class, using the Perl-correct two-argument form. The returned object now claims to come from XML::RSS rather than XML::Parser .

The object model

We have seen that XML::RSS creates a parser and reads a document conventionally. Where does the module’s real specialization begin: building its own data structures and providing a method interface?

Most of the code in XML::RSS consists of accessor methods that merely insert data into, or retrieve it from, the structure it builds. XML::RSS uses nothing more complicated than nested hash references. Their keys usually carry the element or attribute names used when converting to an actual document. To reconcile RSS versions, it uses maps to map the different names. Here is such a map for RSS 0.9:

my %v0_9_ok_fields = (    
    channel => {
        title => '',
        description => '',
        link => '',
        },
    image => {
        title => '',
        url => '',
        link => ''
        },
    textinput => {
        title => '',
        description => '',
        name => '',
        link => ''
        },
    items => [],
    num_items => 0,
    version => '',
    encoding => ''
);

“Just a few hash references” was slightly exaggerated: the top-level element items must hold an array reference. Other keys have scalar values, represented here by empty strings, with one exception: num_items, which RSS does not define. It contains the item-array length and exists purely for convenience, allowing $ref->{num_items} instead of @{$ref->{items}}.

Such an auxiliary key requires programmers to keep it up to date. Which approach is better is a matter of taste, beyond this book’s scope.

Besides needing some value for each hash key (undef is merely a special case of “some”), maps have other uses. Each hash also guides a module function and acts as a template for the generated or correct data structure. Keeping this in mind, let us see what happens when an XML::Parser instance builds a new document.

Input: user or file

Once we create the XML::RSS object, it is ready to output an RSS document, largely thanks to its proud parent, XML::Parser. The user need only call parse or parsefile to fill the object with data almost automatically.

Some objects, however, live long, productive lives without ever consuming an existing XML document. RSS users often create documents from scratch or convert input from a different format. This is where accessor methods help.

Suppose, for example, we have an SQL database of weblog entries to convert to RSS. This short script does it:

#!/usr/bin/perl        

# Umwandlung der letzten 15 Einträge von Dr. Thalers Weblog in ein
# RSS-1.0-Dokument, das auf STDOUT ausgegeben wird.

use warnings;
use strict;

use XML::RSS;
use DBIx::Abstract;

my $MAX_ENTRIES = 15;

my ($output_version) = @ARGV;
$output_version ||= '1.0';
unless ($output_version eq '1.0' or $output_version eq '0.9'
                        or $output_version eq '0.91') {
      die "Usage: $0 [version]\n" .
        "Wobei [version] eine gültige RSS-Version sein muß, der das auszugebende\n" .
        "Dokument entsprechen muß: 0.9, 0 .91 oder 1.0 (Vorgabe).\n";
}

my $dbh = DBIx::Abstract->connect({dbname=>'weblog',
                        user=>'thaler',
                        password=>'thomas'})
      or die "Verbindung zur Datenbank konnte nicht hergestellt werden.\n";
my ($date) = $dbh->select('max(date_added)',
                        entry')->fetchrow_array;
my ($time) = $dbh->select('max(time_added)',
                        'entry')->fetchrow_array;
my $time_zone = "MESZ";
my $rss_time = "${date}$time $time_zone";
# Die Ausgangszeit ist der Beginn des Web-Log, die Synchronisationsinformationen
# benötigen diese Angabe.
my $base_time = "2001-03-03 00:00:00 $time_zone";

# Das folgende ist für RSS-Version 1.0 implementiert. Einige Metainformationen gehen
# in 'modules', d.h. sie haben ihre eigenen Namensräume wie 'dc' (Dublin Core) oder
# 'syn' (für RSS Sychronisation), aber glücklicherweise schadet es nicht, wenn das
# Dokument etwas komplizierter wird, wie wir unten noch sehen werden ...

my $rss = XML::RSS->new(version=>'1.0', output=>$output_version);

$rss->channel(
                        title=>'Thomas T’s Tagebuch',
                        link=>'http://www.jmac.org/linklog/',
                        description=>"Das Online-Forschungsjournal von Dr. Thomas Thaler",
                        dc=> {
                                date=>$rss_time,
                                creator=>'llink@jmac.org',
                                rights=>'Copright 2002 Dr. Thomas Thaler',
                                language=>'de-DE',
                                },
                        syn=> {
                                updatePeriod=>'daily',
                                updateFrequency=>1,
                                updateBase=>$base_time,
                        },
);

$dbh->query("select * from entry order by id desc limit $MAX_ENTRIES");
while (my $entry = $dbh->fetchrow_hashref) {
        # Ersetze die für XML kritischen Zeichen durch Entities
        $$entry{entry} =~ s/&/&/g;
        $$entry{entry} =~ s/</&lt;/g;
        $$entry{entry} =~ s/'/&apos;/g;
        $$entry{entry} =~ s/"/&quot;/g;
        $rss->add_item(
                title=>"$$entry{date_added} $$entry{time_added}",
                link=>"http://www.jmac.org/weblog?$$entry{date_added}#$$entry{time_added}",
                description=>$$entry{entry},
                        );
}

# Ergebnis wird einfach nach STDOUT geschrieben.
print $rss->as_string;

Did you notice any XML? Neither did we. We did use regular expressions to escape XML special characters. Otherwise, we read a database and populated an object through method calls, specifically within a loop calling the method add_item. Each call took a hash of ordinary strings as its only argument. Although the program exploits all RSS offers, producing the RSS file appears to have little to do with XML.

Output as simply as possible

Incidentally, XML::RSS uses no helper such as XML::Writer to generate XML. It simply builds a long string filled from the hash maps by running through if-, else- and elsif constructs, making extensive use of the .= concatenation operator. If you consider external XML-writing modules unnecessary, this is an alternative. It saves effort and gives full control, at a significant cost in safety: you must ensure well-formedness yourself. (A module such as XML::RSS, responsible for both input and output, may shift some of this work to careful input validation.)

  

  

 

 

 

back to top