Menu

Overview of Expat

September 1, 1999

Clark Cooper

Expat is a stream-oriented parser. You register callback (or handler) functions with the parser and then start feeding it the document. As the parser recognizes parts of the document, it will call the appropriate handler for that part (if you've registered one). The document is fed to the parser in pieces, so you can start parsing before you have the whole document. This also allows you to parse really huge documents that won't fit into memory.

Expat can be intimidating due to the many kinds of handlers and options you can set. But you only need to learn four functions in order to do 80% of what you'll want to do with it:

XML_ParserCreate
Create a new parser object.


XML_SetElementHandler
Set handlers for start and end tags.


XML_SetCharacterDataHandler
Set handler for text.


XML_Parse
Pass a buffer full of document to the parser

These functions and others are described in the reference part of this article. The reference section also describes in detail the parameters passed to the different types of handlers.

This subdirectory contains the Makefile and source code for examples used in this article.

Let's look at a very simple example program that only uses three of the above functions. (It doesn't need to set a character handler.) The program outline.c prints an element outline, indenting child elements to distinguish them from the parent element that contains them. The start handler does all the work. It prints two indenting spaces for every level of ancestor elements, then it prints the element and attribute information. Finally it increments the global Depth variable.


int Depth;



void

start(void *data, const char *el, const char **attr) {

  int i;



  for (i = 0; i < Depth; i++)

    printf("  ");



  printf("%s", el);



  for (i = 0; attr[i]; i += 2) {

    printf(" %s='%s'", attr[i], attr[i + 1]);

  }



  printf("\n");

  Depth++;

}  /* End of start handler */

The end tag simply does the bookkeeping work of decrementing the Depth.


void

end(void *data, const char *el) {

  Depth--;

}  /* End of end handler */

After creating the parser, the main program just has the job of shoveling the document to the parser so that it can do its work.

Building expat

One of the problems with using expat is that isn't packaged as a library. Instead there are four separate object files that you have to link into your application. The Makefile that builds the sample applications in this article can be used as a template.

Compile time conditionals

There are a few compiletime macros that control how the compiled expat behaves:

XML_UNICODE
Use UTF-16 internally and pass strings to application using UTF-16 instead of UTF-8. This changes the type definition of XML_Char, which would otherwise be defined as char.


XML_UNICODE_WCHAR_T
Use UTF-16 internally as declared as wchar_t from <stddef.h>. and pass strings to application this way. This sets XML_UNICODE if it wasn't already set. If XML_UNICODE is set but not XML_UNICODE_WCHAR_T, then the UTF-16 is stored as unsigned short.


XML_DTD
Include code to parse external DTD.


XML_NS
Do lexical checking of namespaces


XML_BYTE_ORDER
Set this to "12" for little-endian machines (machines that have the least significant byte first) and to "21" for big-endian (most significant byte first.)


XML_MIN_SIZE
Makes a parser that's smaller but that, in general, will run slower.

If your system doesn't have memmove, but does have bcopy, then you'll want to have a macro that redfines memmove to bcopy. There's a Makefile macro that does this in the sample Makefile, XP_MM. You'll have to uncomment its definition in order to have it take effect.

Working with Expat

As I mentioned in the overview section, the document is fed to the parser a piece at a time. It is completely up to the calling application how much of the document to fit into a piece. The sample program, line demonstrates this. It passes a line at a time to the parser and then reports start, end, text, and processing instruction events. By interactively typing in a document into this program, you may start to obtain an intuitive feel for how the parser is working.

Walking through a document hierarchy with a stream oriented parser will require a good stack mechanism in order to keep track of current context. For instance, to answer the simple question, "What element does this text belong to?" requires a stack, since the parser may have descended into other elements that are children of the current one and has encountered this text on the way out.

The things you're likely to want to keep on a stack are the currently opened element and it's attributes. You push this information onto the stack in the start handler and you pop it off in the end handler.

For some tasks, it is sufficient to just keep information on what the depth of the stack is (or would be if you had one.) The outline program shown above presents one example. Another such task would be skipping over a complete element. When you see the start tag for the element you want to skip, you set a skip flag and record the depth at which the element started. When the end tag handler encounters the same depth, the skipped element has ended and the flag may be cleared. If you follow the convention that the root element starts at 1, then you can use the same variable for skip flag and skip depth.


void

init_info(Parseinfo *info) {

  info->skip = 0;

  info->depth = 1;

  /* Other initializations here */

}  /* End of init_info */



void

rawstart(void *data, const char *el, const char **attr) {

  Parseinfo *inf = (Parseinfo *) data;



  if (! inf->skip) {

    if (should_skip(inf, el, attr)) {

      inf->skip = inf->depth;

    }

    else

      start(inf, el, attr);     /* This does rest of start handling */

  }



  inf->depth++;

}  /* End of rawstart */



void

rawend(void *data, const char *el) {

  Parseinfo *inf = (Parseinfo *) data;



  inf->depth--;



  if (! inf->skip)

    end(inf, el);              /* This does rest of end handling */



  if (inf->skip == inf->depth)

    inf->skip = 0;

}  /* End rawend */



Notice in the above example the difference in how depth is manipulated in the start and end handlers. The end tag handler should be the mirror image of the start tag handler. This is necessary to properly model containment. Since, in the start tag handler, we incremented depth after the main body of start tag code, then in the end handler, we need to manipulate it before the main body. If we'd decided to increment it first thing in the start handler, then we'd have had to decrement it last thing in the end handler.

Communicating between handlers

In order to be able to pass information between different handlers without using globals, you'll need to define a data structure to hold the shared variables. You can then tell expat (with the XML_SetUserData function) to pass a pointer to this structure to the handlers. This is typically the first argument received by most handlers.

Namespace Processing

When the parser is created using the XML_ParserCreateNS, function, expat performs namespace processing. Under namespace processing, expat consumes xmlns and xmlns:... attributes, which declare namespaces for the scope of the element in which they occur. This means that your start handler will not see these attributes. Your application can still be informed of these declarations by setting namespace declaration handlers with XML_SetNamespaceDeclHandler.

Element type and attribute names that belong to a given namespace are passed to the appropriate handler in expanded form. This expanded form is a concatenation of the namespace URI, the separator character (which is the 2nd argument to XML_ParserCreateNS), and the local name (i.e. the part after the colon). Names with undeclared prefixes are passed through to the handlers unchanged, with the prefix and colon still attached. Unprefixed attribute names are never expanded, and unprefixed element names are only expanded when they are in the scope of a default namespace.

You can set handlers for the start of a namespace declaration and for the end of a scope of a declaration with the XML_SetNamespaceDeclHandler function. The StartNamespaceDeclHandler is called prior to the start tag handler and the EndNamespaceDeclHandler is called before the corresponding end tag that ends the namespace's scope. The namespace start handler gets passed the prefix and URI for the namespace. For a default namespace declaration (xmlns='...'), the prefix will be null. The URI will be null for the case where the default namespace is being unset. The namespace end handler just gets the prefix for the closing scope.

These handlers are called for each declaration. So if, for instance, a start tag had three namespace declarations, then the StartNamespaceDeclHandler would be called three times before the start tag handler is called, once for each declaration.

The namespace.c example demonstrates the use of these features. Like outline.c, it produces an outline, but in addition it annotates when a namespace scope starts and when it ends. This example also demonstrates use of application user data.

Character Encodings

While XML is based on Unicode, and every XML processor is required to recognized UTF-8 and UTF-16 (1 and 2 byte encodings of Unicode), other encodings may be declared in XML documents or entities. For the main document, an XML declaration may contain an encoding declaration:

<?xml version="1.0" encoding="ISO-8859-2"?>

External parsed entities may begin with a text declaration, which looks like an XML declaration with just an encoding declaration:

<?xml encoding="Big5"?>

With expat, you may also specify an encoding at the time of creating a parser. This is useful when the encoding information may come from a source outside the document itself (like a higher level protocol.)

There are four built-in encodings in expat:

  • UTF-8
  • UTF-16
  • ISO-8859-1
  • US-ASCII

Anything else discovered in an encoding declaration or in the protocol encoding specified in the parser constructor, triggers a call to the UnknownEncodingHandler. This handler gets passed the encoding name and a pointer to an XML_Encoding data structure. Your handler must fill in this structure and return 1 if it knows how to deal with the encoding. Otherwise the handler should return 0. The handler also gets passed a pointer to an optional application data structure that you may indicate when you set the handler.

Expat places restrictions on character encodings that it can support by filling in the XML_Encoding structure. include file:

  1. Every ASCII character that can appear in a well-formed XML document must be represented by a single byte, and that byte must correspond to it's ASCII encoding (except for the characters $@\^'{}~)


  2. Characters must be encoded in 4 bytes or less.


  3. All characters encoded must have Unicode scalar values less than or equal to 65535 (0xFFFF)This does not apply to the built-in support for UTF-16 and UTF-8


  4. No character may be encoded by more that one distinct sequence of bytes

XML_Encoding contains an array of integers that correspond to the 1st byte of an encoding sequence. If the value in the array for a byte is zero or positive, then the byte is a single byte encoding that encodes the Unicode scalar value contained in the array. A -1 in this array indicates a malformed byte. If the value is -2, -3, or -4, then the byte is the beginning of a 2, 3, or 4 byte sequence respectively. Multi-byte sequences are sent to the convert function pointed at in the XML_Encoding structure. This function should return the Unicode scalar value for the sequence or -1 if the sequence is malformed.

One pitfall that novice expat users are likely to fall into is that although expat may accept input in various encodings, the strings that it passes to the handlers are always encoded in UTF-8. Your application is responsible for any translation of these strings into other encodings.

Handling External Entity References

Expat does not read or parse external entities directly. Note that any external DTD is a special case of an external entity. If you've set no ExternalEntityRefHandler, then external entity references are silently ignored. Otherwise, it calls your handler with the information needed to read and parse the external entity.

Your handler isn't actually responsible for parsing the entity, but it is responsible for creating a subsidiary parser with XML_ExternalEntityParserCreate that will do the job. This returns an instance of XML_Parser that has handlers and other data structures initialized from the parent parser. You may then use XML_Parse or XML_ParseBuffer calls against this parser. Since external entities my refer to other external entities, your handler should be prepared to be called recursively.

Parsing DTDs

In order to parse parameter entities, the macro XML_DTD, must be defined when expat is compiled. In addition, after creating the parser and before starting the parse, you must call XML_SetParamEntityParsing with one of the following arguments:

XML_PARAM_ENTITY_PARSING_NEVER
Don't parse parameter entities or the external subset


XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE
Parse parameter entites and the external subset unless standalone was set to "yes" in the XML declaration.


XML_PARAM_ENTITY_PARSING_ALWAYS
Always parse parameter entities and the external subset

In order to read an external subset, you also have to set an external entity reference handler as described above.