[ < ] | [ > ] |  | [ << ] | [ Up ] | [ >> ] |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

# 4. The SAX module

> 4.1 Description |  |
> 4.2 Examples |  |
> 4.3 The SAX parser |  |
> 4.4 The SAX handlers |  |

[ < ] | [ > ] |  | [ << ] | [ Up ] | [ >> ] |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

## 4.1 Description

Parsing XML streams can be done with two different methods. They each have their pros and cons. Although the simplest, and probably most usual way to manipulate XML files is to represent them in a tree and manipulate it through the DOM interface (see next chapter).

The Simple API for XML is an other method that can be used for parsing. It is based on a callbacks mechanism, and doesn't store any data in memory (unless of course you choose to do so in your callbacks). It can thus be more efficient to use SAX than DOM for some specialized algorithms. In fact, this whole Ada XML library is based on such a SAX parser, then creates the DOM tree through callbacks.

Note that this module supports the second release of SAX (SAX2), that fully supports namespaces as defined in the XML standard.

SAX can also be used in cases where a tree would not be the most efficient representation for you data. There is no point in building a tree with DOM, then extracting the data and freeing the tree occupied by the tree. It is much more efficient to directly store your data through SAX callbacks.

With SAX, you register a number of callback routines that the parser will call them when certain conditions occur.

This documentation is in no way a full documentation on SAX. Instead, you should refer to the standard itself, available at http://www.megginson.com/SAX/.

Some of the more useful callbacks are `Start_Document`, `End_Document`, `Start_Element`, `End_Element`, `Get_Entity` and `Characters`. Most of these are quite self explanatory. The characters callback is called when characters outside a tag are parsed.

Consider the following XML file:

    <?xml version="1.0"?>
    <body>
      <h1>Title</h1>
    </body>

The following events would then be generated when this file is parsed:

    Start_Document           Start parsing the file
    Start_Prefix_Mapping     (handling of namespaces for "xml")
    Start_Prefix_Mapping     Parameter is "xmlns"
    Processing_Instruction   Parameters are "xml" and "version="1.0""
    Start_Element            Parameter is "body"
    Characters               Parameter is ASCII.LF & "  "
    Start_Element            Parameter is "h1"
    Characters               Parameter is "Title"
    End_Element              Parameter is "h1"
    Characters               Parameter is ASCII.LF & "  "
    End_Element              Parameter is "body"
    End_Prefix_Mapping       Parameter is "xmlns"
    End_Prefix_Mapping       Parameter is "xml"
    End_Document             End of parsing

As you can see, there is a number of events even for a very small file. However, you can easily choose to ignore the events you don't care about, for instance the ones related to namespace handling.

[ < ] | [ > ] |  | [ << ] | [ Up ] | [ >> ] |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

## 4.2 Examples

There are several cases where using a SAX parser rather than a DOM parser would make sense. Here are some examples, although obvisouly this doesn't include all the possible cases. These examples are taken from the documentation of libxml, a GPL C toolkit for manipulating XML files.

- Using XML files as a database

  One of the common usage for XML files is to use them as a kind of basic database, They obviously provide a strongly structured format, and you could for instance store a series of numbers with the following format.

      <array> <value>1</value> <value>2</value> ....</array>

  In this case, rather than reading this file into a tree, it would obviously be easier to manipulate it through a SAX parser, that would directly create a standard Ada array while reading the values.

  This can be extended to much more complex cases that would map to Ada records for instance.

- Large repetitive XML files

  Sometimes we have XML files with many subtrees of the same format describing different things. An example of this is an index file for a documentation similar to this one. This contains a lot (maybe thousands) of similar entries, each containing for instance the name of the symbol and a list of locations.

  If the user is looking for a specific entry, there is no point in loading the whole file in memory and then traverse the resulting tree. The memory usage increases very fast with the size of the file, and this might even be unfeasible for a 35 megabytes file.

- Simple XML files

  Even for simple XML files, it might make sense to use a SAX parser. For instance, if there are some known constraints in the input file, say there are no attributes for elements, you can save quite a lot of memory, and maybe time, by rebuilding your own tree rather than using the full DOM tree.

However, there are also a number of drawbacks to using SAX:

- SAX parsers generally require you to write a little bit more code than the DOM interface
- There is no easy way to write the XML data back to a file, unless you build your own internal tree to save the XML. As a result, SAX is probably not the best interface if you want to load, modify and dump back an XML file.

  Note however than in this Ada implementation, the DOM tree is built through a set of SAX callbacks anyway, so you do not lose any power or speed by using SAX.

[ < ] | [ > ] |  | [ << ] | [ Up ] | [ >> ] |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

## 4.3 The SAX parser

The basic type in the SAX module is the SAX.Readers package. It defines a tagged type, called `Reader`, that represents the SAX parser itself.

Several features are define in the SAX standard for the parsers. They indicate which behavior can be expected from the parser. The package `SAX.Readers` defines a number of constant strings for each of these features. Some of these features are read-only, whereas others can be modified by the user to adapt the parser. See the `Set_Feature` and `Get_Feature` subprograms for how to manipulate them.

The main primitive operation for the parser is `Parse`. It takes an input stream for argument, associated with some XML data, and then parses it and calls the appropriate callbacks. It returns once there are no more characters left in the stream.

Several other primitive subprograms are defined for the parser, that are called the callbacks. They get called automatically by the `Parse` procedure when some events are seen.

As a result, you should always override at least some of these subprogram to get something done. The default implementation for these is to do nothing, exception for the error handler that raises Ada exceptions appropriately.

An example of such an implementation of a SAX parser is available in the DOM module, and it creates a tree in memory. As you will see if you look at the code, the callbacks are actually very short.

Note that internally, all the strings are encoded with a unique character encoding scheme, that is defined in the file ``sax-encodings.ads'`. The input stream is converted on the fly to this internal encoding, and all the subprograms from then on will receive and pass parameters with this new encoding. You can of course freely change the encoding defined in the file ``sax-encodings.ads'`.

[ < ] | [ > ] |  | [ << ] | [ Up ] | [ >> ] |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

## 4.4 The SAX handlers

We do not intend to document the whole set of possible callbacks associated with a SAX parser. These are all fully documented in the standard itself, and there is little point in duplicating this information.

However, here is a list of the most frequently used callbacks, that you will probably need to override in most of your applications.

`Start_Document`
  This callback, that doesn't receive any parameter, is called once, just before parsing the document. It should generally be used to initialize internal data needed later on. It is also garanteed to be called only once per input stream.

`End_Document`
  This one is the reverse of the previous one, and will also be called only once per input stream. It should be used to release the memory you have allocated in Start_Document.

`Start_Element`
  This callback is called every time the parser encounters the start of an element in the XML file. It is passed the name of the element, as well as the relevant namespace information. The attributes defined in this element are also passed as a list. Thus, you get all the required information for this element in a single function call.

`End_Element`
  This is the opposite of the previous callback, and will be called once per element. Calls to `Start_Element` and `End_Element` are garanteed to be properly nested (ie you can't see the end of an element before seeing the end of all its nested children.

`Characters and Ignore_Whitespace`
  This procedure will be called every time some character not part of an element declaration are encounted. The characters themselves are passed as an argument to the callback. Note that the white spaces (and tabulations) are reported separately in the Ignorable_Spaces callback in case the XML attribute `xml:space` was set to something else than `preserve` for this element.

You should compile and run the ``testsax'` executable found in this module to visualize the SAX events that are generated for a given XML file.

[ << ] | [ >> ] |  |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

This document was generated by Emmanuel Briot on December, 20 2001 using texi2html