XML technologies / XML / Perl & XML / SAX / Resolving external entities

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

By default, the parser replaces all entity references with their assigned values, usually exactly what we want. In exceptional cases, such as our filter example, we would prefer to preserve the references. As we have seen, this is easy: write a custom handler method entity_reference( ) that outputs references without resolving them. We do not yet know how to restore the default behavior, perhaps with slight changes. The parser wants to locate files and insert their content into the stream. Apart from our filter example, why might we change this?

Splitting documents into several files is convenient, especially for very large documents. Suppose we write a long book in XML, with each chapter in a separate file. External entities make this simple:

<?xml version="1.0"?>
<doctype book [
    <!ENTITY intro-kapitel SYSTEM "kapitel/intro.xml">
    <!ENTITY nudel-kapitel SYSTEM "kapitel/nudel.xml">
    <!ENTITY saucen-kapitel SYSTEM "kapitel/saucen.xml">
    <!ENTITY suppen-kapitel SYSTEM "kapitel/suppen.xml"> ]>
    <book>
        <title>Das Kochbuch für lange Hacker-Sessions</title>
        &intro-kapitel;
        &nudel-kapitel;
        &saucen-kapitel;
        &suppen-kapitel;
    </book>

Our previous filter would resolve the external entities and output the book as one piece, losing the chapter-file structure. Restoring it would require manual work. Fortunately, we can control external entity resolution by writing a handler called resolve_entity( ) .

This handler receives four properties: Name, the entity name; SystemId and PublicId, identifying the file’s location; and Base, the base URL for relative URLs. Unlike other handlers, it must return a result to control the parser’s next action. Returning undef tells the parser to load and process the file normally. Otherwise, return a hash describing an alternative file to load. This hash has the same structure as the one passed to the parser’s parse( ) method. For example, it can contain a SystemId key holding a filename or URL, or a text string for the parser to read. Consider this example:

sub resolve_entity {     
     my( $self, $props ) = @_;
     if( exists( $props->{ SystemId }) and
        open( ENT, $props->{ SystemId })) {
     my $entval = '<?start-file ' . $props->{ SystemId } . '?>';
     while( <ENT> ) { $entval .= $_; }
     close ENT;
     $entval .= '<?end-file ' . $props->{ SystemId } . '?>';
     return { String => $entval };
     } else {
        return undef;
     }
}

This method opens the actual entity and reads it into a string, which is then passed to the parser. First, however, two processing instructions are added at its beginning and end. These instructions could later identify the file boundaries, allowing another filter, for example, to separate the documents again.

  

  

 

 

 

back to top