XML technologies / XML / Perl & XML / XML basics: Reading and writing / XML parsers

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

Reading and writing files is fundamental to a programming language. Traditionally, however, this happened at a fairly low level: individual characters were read, or at best whole lines, then analyzed with regular expressions. Raw text is an unpleasant business, without clear rules separating its parts. We can rarely distinguish more than lines or tab-separated columns. So many data-storage formats arose that the builders of the Tower of Babel would turn pale with envy. This problem was a major reason for developing XML, with clear rules delimiting data, building hierarchies and connecting parts predictably and unambiguously. A program following these rules can read any well-formed XML document as though someone had put a Babel fish (Note: readers of The Hitchhiker’s Guide to the Galaxy by Douglas Adams will remember a Babel fish as a living translator for any language, about olive-sized. Put headfirst into your ear, it fits exactly into the ear canal.) in its ear.

Where do we get this Babel fish? The XML parser is a program or library reading XML documents and presenting them to us. It may deliver an event stream or, if requested, a large complex data object giving direct access to document parts. Input may come from one or more files, a character stream or a string. The document may be seasoned with entity references: leave them for a spicy result, or have the parser substitute entities for a milder result, hiding them from us entirely. Parts may originate outside our computer, in a remote corner of the Internet. The document may be written in ISO-8859-1 or a Japanese character set. Users need worry little about these matters—fortunately, since we are those users. The parser handles all details, an abstract tunnel from physical storage to the crystal-clear representation our subroutines receive.

An XML parser bridges marked-up text and a prepared format our programs can handle. Perl ultimately exposes familiar hash references, array references and scalars. XML can be complex, combining files and streams and containing unexplored regions, entities, that must be navigated. We can nevertheless rely on a parser accepting only clean XML and rejecting well-formedness violations. Its output must preserve structure: order, boundaries and associations between names and data. Ideally, it hides irrelevant details such as input filenames and encodings. That is a lot of work. To summarize its duties:

XML mixes data and markup, so the parser first separates these from the character stream. Special characters distinguish instructions from data, particularly less-than and greater-than (< and >) for elements, comments and PIs. Ampersand (&) and semicolon (;) must also delimit entity references correctly. The parser knows when instructions are permitted. For example, an element containing text or other elements needs both start- and end-tags. This knowledge lets it quickly split the stream into the parts described by XML markup.

The next task replaces placeholders. Entity references must be resolved. Early in parsing, the processor lists declared placeholders, associating short identifiers, entity names, with the entity. Entities are declared by name in the DTD; values are read there or retrieved through a URL. Values may contain further references, requiring several iterations for complete resolution.

Sometimes resolution is undesirable. For small edits followed by writing the document back, you may want to disable resolution or handle it with your own code. You might resolve external entities at remote URLs because you do not control them, but leave internal ones intact. Most parsers support such tricks; none permits undeclared references.

This brings us to the third task. If external resolution is allowed, the parser gathers every required document, local or remote, joining separate parts into one large document. Physical origin rarely matters to applications, so origin information is discarded as parts are incorporated.

Interpreting markup may expose syntax errors. XML makes these easy to detect, with strict rules for everything from attributes to empty elements. This fragment has an obvious error: the start-tag of element <Dekret> contains an invalid attribute assignment. The value “sofort” has an opening double quote but no closing one. The end-tag also has an error. Can you spot it?

<Dekret gueltig="sofort>Alle Motorräder sind rot anzustreichen.</Dekret<

Such errors leave little choice but to stop: continuing makes little sense. Eliminating ambiguity is fundamental to XML. Guessing the intended document (Note: Most HTML browsers detect, ignore or even correct such errors. This sounds convenient, but in practice encourages careless authors and lowers web information quality. Honestly, would you fix errors if you did not have to?) would begin a slide toward uncertainty and weaken trust in the program’s accuracy. XML’s designers instead required an error message and a halt, a wise choice in our view. A document read without complaint is called well-formed.

What are “grammar errors”? These concern validating parsers. A document is valid when it passes the tests imposed by a DTD. XML languages and applications often use DTDs to extend the minimum standards of well-formedness and enforce an order of elements and text. The W3C, for example, provides a DTD describing XHTML, XML-conformant HTML. Its DTD lists every allowed element, its location and content. It is grammatically correct to place an element <p> inside a <body> , but the same <p> does not belong inside <head>. Do not even think of using an element <Peanuts>: it is undeclared. (Note: If you insist on an element <Peanuts> in your XHTML, create your own DTD, preferably importing the real DTD through an entity reference and adding your elements. The result is not official XHTML, but a kind of subclass.) A single such error makes the document invalid. It can be well-formed without being valid against the DTD. Such precision is often more burden than help, but available when needed.

Finally, parsers must deliver information suitably to programs or end users. Many approaches exist, and much of this book examines them. Broadly, these categories are already distinguishable:

Event stream

A parser can produce events, converting markup sequences into a more abstract sequence with preprocessed, more easily interpreted data.

Object representation

Parsers can also build a structure whose objects mirror the document’s nested information. This demands considerable resources, but is often easier and more pleasant: navigate the tree freely instead of waiting for unread data.

Hybrid forms

Hybrid parsers use built-in intelligence to identify a particular document portion and build an object containing only that portion.

Example: Checking well-formedness

Enough abstraction: let us get our hands dirty and write a parser solely checking whether a document is well-formed XML. It cannot be simpler: no further processing, just a yes/no result.

We want to demystify XML processing, ultimately text processing, but also show that writing a correct Perl parser, or one in any language, takes substantial work. Better spend that effort on interesting code and use an existing parser module. We will implement only a fraction of a real Perl XML parser.

Warning! Play with this program as much as you like, but never use it for serious work! It illustrates parser behavior rather than solving Perl XML processing. It is incomplete and can give wrong results, as we will show. The rest of the book covers real, usable parsers.

The program mainly consists of a loop using regular expressions to recognize and extract markup. It continues until no text remains, indicating well-formedness. If no expression matches, the document is not well-formed. Other tests can stop it, such as an end-tag not matching the current start-tag. It is not a real solution, but shows how a parser might work.

The function below checks a string of XML text and returns a Boolean. Pattern variables make the regular expressions clearer. For example, string $ident contains a pattern recognizing XML identifiers such as element names, attribute names and processing-instruction targets.

Example: A rudimentary XML parser

sub ist_wohlgeformt {
     my $text = shift; # zu prüfender XML-Text     
       
     # Verwendete Muster
     my $ident = '[:_A-Za-z][:A-Za-z0-9\-\._]*'; # Bezeichner (Identifier)
     my $optsp = '\s*'; # optionales Leerzeichen
     my $att1 = "$ident$optsp=$optsp\"[^\"]*\""; # Attribut mit doppelten Anführungszeichen
     my $att2 = "$ident$optsp=$optsp'[^']*'"; # Attribut mit einfachen Anführungszeichen
     my $att = "($att1|$att2)"; # beliebiges Attribut
       my @elements = (); # Stack mit offenen Elementen
       
     # In einer Schleife den String durchlaufen und XML-Markup extrahieren
     while( length($text) ) {
       
          # Ist es ein leeres Element?
          if( $text =~ /^&($ident)(\s+$att)*\s*\/>/ ) {
          $text = $';
            
          # Ist es das Start-Tag eines Elements?
          } elsif( $text =~ /^&($ident)(\s+$att)*\s*>/ ) {
          push( @elements, $1 );
          $text = $';
          # Ist es das End-Tag eines Elements?
          } elsif( $text =~ /^&\/($ident)\s*>/ ) {
          return unless( $1 eq pop( @elements ));
          $text = $';

          # Ist es ein Kommentar?
          } elsif( $text =~ /^&!--/ ) {
          $text = $';
          # Rest des Kommentars entfernen
          if( $text =~ /-->/ ) {
          $text = $';
          return if( $` =~ /--/ ); # Kommentare dürfen kein '--' enthalten
          } else {
          return;
          }
          
          # Ist es ein CDATA-Abschnitt?
          } elsif( $text =~ /^&!\[CDATA\[/ ) {
          $text = $';
          # Rest des CDATA-Abschnitts entfernen
          if( $text =~ /\]\]>/ ) {
          $text = $';
          } else {
          return;
          }
          
          # Ist es eine PI?
          } elsif( $text =~ m|^&\?$ident\s*[^\?]+\?>| ) {
          $text = $';
          # Sind es zusätzliche Leerzeichen?
          # (zum Beispiel außerhalb des Wurzelelements)
          } elsif( $text =~ m|^\s+| ) {
          $text = $';
     
          # Sind es Textdaten?
          } elsif( $text =~ /(^[^&&>]+)/ ) {
          my $data = $1;
          # Textdaten sind nur innerhalb eines Elements erlaubt
          return if( $data =~ /\S/ and not( @elements ));
          $text = $';
          
          # Ist es eine Entityreferenz?
          } elsif( $text =~ /^&$ident;+/ ) {
          $text = $';
          
          # Nein, es ist etwas Unerwartetes
          } else {
          return;
          }
     }
     return if( @elements ); # Der Stack sollte jetzt leer sein.
     return 1;
}

Perl arrays are useful partly because they implement abstract computing concepts. (Note: Mastering Algorithms with Perl by Jon Orwant, Jarkko Hietaniemi and John Macdonald, O’Reilly, devotes a chapter to this.) Here we use a stack, simply an array accessed only with push( ) and pop( ). Its last-in, first-out (LIFO) order conveniently tracks open elements: the last opened is the next to close. Push start-tags, pop the latest for each end-tag, and compare. Well-formedness requires their names to match.

The stack represents open tags from root to current element. Elements are processed in document order. As a tree traversal, this goes from trunk to the first branch’s tip, back to the latest fork, along the next branch and so on. This is called depth-first traversal, the canonical way of processing XML documents.

A few extra tests extend the loop. Comment checks, for example, are more complex because -- must not occur inside comments.

  • An identifier, such as an element or attribute name, is invalid, for example 12bla, -fasel or ...

  • Non-whitespace text occurs outside the root element.

  • An end-tag does not match the latest start-tag.

  • An attribute value is missing, unquoted, or mixes single and double quotes.

  • An empty element lacks the closing slash (/ ).

  • Text contains an invalid character such as a lone ampersand (&) or less-than (<).

  • Other invalid markup is found, such as <blubb< or < ?blobb?>.

Try some edge cases. Here are suggestions. The shortest well-formed document is probably:

 <:-/> 

The next document should cause an error. Hint: inspect the end-tag of <nachricht>.

<memo>
   <an>mich selbst</an>
   <nachricht>Vergiß nicht, den Wagen zu mähen und
   den Rasen zu waschen.<nachricht>
</memo>

Documents may have many other syntax errors. Our program finds most, not all. There should be only one root, but it accepts several:

<root>Ich bin das einzig wahre Wurzelelement!</root>
<root>Nein, ich bin es!</root>
<root>Öh, äh...</root>

More problems? The parser cannot handle DTDs. Validating documents often begin with a DTD declaration and perhaps entities. A specialized loop could process and skip the DTD’s separate syntax.

The biggest flaw is missing entity resolution. It checks reference syntax but never substitutes text. Entities may contain arbitrary markup, perhaps from huge external files, and nested references requiring repeated resolution. Undeclared entities also go unchecked because DTD syntax is unsupported. Entities can hide many errors. Possible fixes are:

  1. Add a loop parsing the DTD before the document, checking and storing entity declarations for later resolution.

  2. If a DTD exists, invoke that loop first to build the declaration list.

  3. Resolve every reference in the main loop, parsing and checking substituted entities and resolving any further references. This can become tangled, with nested loops, recursion and other complex programming.

A simple parser quickly becomes a complex tangle. Its theory is easy, its practice difficult. This exercise illustrated parsing problems, not an invitation to continue building one. We strongly recommend using the extensive work already invested in real parsers. Let us leave the dark ages for the happier era of ready-made parsers.

  

  

 

 

 

back to top