XML technologies / XML / Perl & XML / Perl and XML / XML made simple with XML::Simple

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

Some people consider XML the invention of a disturbed mind bent on humanity’s extinction. Sometimes one understands them: markup’s angle brackets and slashes hardly soothe the eyes. Add nested elements, node types and DTDs, pleasantly simple compared with XML Schema, and you may miss CSV (Comma Separated Values) files—one record per line, columns separated by delimiters—and their parser, the function split.

Here is a secret: writing XML software is not hard. A toolbox hides annoying parser and structure-building details behind APIs learned in minutes. Full complexity is available when needed, but not mandatory. XML can be simple or deep according to the application; simple tasks have simple tools.

To demonstrate, consider Grant McLean’s simple module XML::Simple. Minimal learning yields surprisingly good XML results.

A typical program reads XML, changes something and writes it back. That is precisely what XML::Simple does. One call loads XML as nested hashes representing elements and data. After modifications, another call writes it to a file.

Let us try it. First load XML::Simple into the program using use:

 use XML::Simple; 

This makes XML::Simple define these two functions:

XMLin( )

Reads XML from a file or string and builds a structure of its data and elements, returning a hash reference.

XMLout( )

Takes a hash reference encoding a document, converts it to correct XML and returns that text string.

You can also build a document from scratch with hashes, arrays and strings, perhaps necessarily for a new file. Avoid circular references or the module will fail.

Suppose the boss wants to email a group using WarbleSoft’s well-known SpamChucker mailing-list manager. It imports and exports XML address lists. The boss has a special request: uppercase customer names. We need to read XML, uppercase names and save the changes.

Accepting the challenge, inspect the XML structure in this example mailing list.

 

Example: SpamChucker mailing-list XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<spam-document version="3.5" timestamp="2002-05-13 15:33:45">
  <!-- Automatisch erzeugt durch WarbleSoft Spam Version 3.5 -->
  <customer>
    <first-name>Johannes</first-name>
    <surname>Jäger</surname>
    <address>
<street>Murmelstr. 17</street>
<city>Metzingen</city>
<state>Baden-Württemberg</state>
<zip>72555</zip>
</address>
    <email>jjaeger@gmx.de</email>
    <age>42</age>
  </customer>
  <customer>
    <first-name>Henrietta</first-name>
    <surname>Kittinger</surname>
    <address>
<street>Ermsstr. 2</street>
<city>Eningen</city>
<state>Baden-Württemberg</state>
<zip>72800</zip>
</address>
    <email>kitty@web.de</email>
    <age>37</age>
  </customer>
</spam-document>

A glance at documentation for XML::Simple ( perldoc XML::Simple ) lets us write the following script:

Example: Uppercasing customer names

# Dieses Programm liest eine vom WarbleSoft SpamChucker generierte XML-Datei
# und wandelt die Kundennamen in Großbuchstaben um.

# Schalten wir "strict" und "warnings" an, das ist nie ein Fehler.
use strict;
use warnings;

# Import des Moduls XML::Simple
use XML::Simple;

# Die Funktion "XMLin", die von XML::Simple zur Verfügung gestellt wird,
# wandelt die XML-Datei "./kunden.xml" in eine Hashreferenz um.
# Wir verwenden die Option "forcearrays", d.h., Elemente werden immer als Arrayreferenzen
# dargestellt. (Standardmäßig geschieht das nur, wenn sie mehrfach vorkommen.)
my $cust_xml = XMLin('./kunden.xml', forcearray=>1);

# In einer Schleife suchen wir die verschiedenen 'customer'-Elemente, die ihrerseits
# wieder Hashreferenzen sind und als Arrayreferenz unter dem Schlüssel 'customer'
# zu finden sind.
for my $customer (@{$cust_xml->{customer}}) {
# Der Inhalt von 'first-name' und 'surname' wird in Großbuchstaben umgewandelt.
# Das geht sehr einfach mit der in Perl eingebauten Funktion uc( ).
foreach ($customer->{'first-name'}, $customer->{'surname'}) {
$_->[0] = uc($_->[0]);
}
}

# Gib die Hashreferenz wieder als XML-Dokument auf den Bildschirm aus, sinnvollerweise
# schließen wir das Ganze mit einem Zeilenende ab.
print "<?xml version='1.0' encoding='ISO-8859-1'?>\n";
print XMLout($cust_xml);
print "\n";

Running it, somewhat rashly since these are the boss’s data, produces:

<?xml version='1.0' encoding='ISO-8859-1'?>
<spam-document version="3.5" timestamp="2002-05-13 15:33:45">
  <customer>
    <address>
<state>Baden-Württemberg</state>
<zip>72555</zip>
<city>Metzingen</city>
<street>Murmelstr. 17</street>
</address>
    <first-name>JOHANNES</first-name>
    <email>jjaeger@gmx.de</email>
    <surname>JÄGER</surname>
    <age>42</age>
  </customer>
  <customer>
    <address>
<state>Baden-Württemberg</state>
<zip>72800</zip>
<city>Eningen</city>
<street>Ermsstr. 2</street>
</address>
    <first-name>HENRIETTA</first-name>
    <email>kitty@web.de</email>
    <surname>KITTINGER</surname>
    <age>37</age>
  </customer>
</spam-document>

Congratulations: your first XML program works beautifully. Almost. Element order changed because hashes do not retain insertion order, and indentation may be gone. Is that a problem?

Simplicity and completeness conflict, a recurring theme. Decide which markup details require precision. If order matters, you cannot use XML::Simple. The same applies if processing instructions must survive: XML::Simple is unsuitable. Know tools’ capabilities before programming. In our case, SpamChucker accepted the changed file and the boss was happy: it was close enough to satisfy the application.

One might call the changed document semantically equivalent, but that is not quite right: order generally matters in XML. We merely had a tolerant application and user with modest requirements.

You can now consider yourself someone who works with XML and Perl.

Our journey has only begun. Most of the book, with helpful techniques and tips, lies ahead. Not every XML task is this easy, but none is too hard for Perl’s hammer to forge XML’s iron.

  

  

 

 

 

back to top