XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.


Expat Function Reference

September 01, 1999

Expat Functions

Parser Creation


XML_Parser XML_ParserCreate(const XML_Char*encoding)
Construct a new parser. If encoding is non-null, it specifies a character encoding to use for the document. This overrides the document encoding declaration. There are four built-in encodings:
  • UTF-8
  • UTF-16
  • ISO-8859-1
Any other value will invoke a call to the UnknownEncodingHandler.


XML_Parser XML_ParserCreateNS(const XML_Char*encoding, XML_Char sep)
Constructs a new parser that has namespace processing in effect. Namespace expanded element names and attribute names are returned as a concatenation of the namespace URI, sep, and the local part of the name. This means that you should pick a character for sep that can't be part of a legal URI.


XML_Parser XML_ExternalEntityParserCreate(XML_Parser p, const XML_Char *context, const XML_Char *encoding)
Construct a new XML_Parser object for parsing an external general entity. Context is the context argument passed in a call to a ExternalEntityRefHandler. Other state information such as handlers, user data, namespace processing is inherited from the parser passed as the 1st argument. So you shouldn't need to call any of the behavior changing functions on this parser (unless you want it to act differently than the parent parser.)


void XML_ParserFree(XML_Parser p)
Free memory used by the parser. Your application is responsible for freeing any memory associated with UserData.



int XML_Parse(XML_Parser p, const char *s, int len, int isFinal)
Parse some more of the document. The string s is a buffer containing part (or perhaps all) of the document. The number of bytes of s that are part of the document is indicated by len. This means that s doesn't have to be null terminated. It also means that if len is larger than the number of bytes in the block of memory that s points at, then a memory fault is likely. The isFinal parameter informs the parser that this is the last piece of the document. Frequently, the last piece is empty (i.e. len is zero.) If a parse error occurred, it returns 0. Otherwise it returns a non-zero value.


int XML_ParseBuffer(XML_Parser p, int len, int isFinal)
This is just like XML_Parse, except in this case expat provides the buffer. By obtaining the buffer from expat with the XML_GetBuffer function, the application can avoid double copying of the input.


void *XML_GetBuffer(XML_Parser p, int len)
Obtain a buffer of size len to read a piece of the document into. A NULL value is returned if expat can't allocate enough memory for this buffer. This has to be called prior to every call to XML_ParseBuffer. A typical use would look like this:
for (;;) {
  int bytes_read;
  void *buff = XML_GetBuffer(p, BUFF_SIZE);
  if (buff == NULL) {
    /* handle error */

  bytes_read = read(docfd, buff, BUFF_SIZE);
  if (bytes_read < 0) {
    /* handle error */

  if (! XML_ParseBuffer(p, bytes_read, bytes_read == 0)) {
    /* handle parse error */

  if (bytes_read == 0)

Handler Setting

Although handlers are typically set prior to parsing and left alone, an application may choose to set or change the handler for a parsing event while the parse is in progress. For instance, your application may choose to ignore all text not descended from a para element. One way it could do this is to set the character handler when a para start tag is seen, and unset it for the corresponding end tag.

A handler may be unset by providing a NULL pointer to the appropriate handler setter. None of the handler setting functions have a return value.

Your handlers will be receiving strings in arrays of type XML_Char. This type is defined in xmlparse.h and is conditional upon the setting of either of the XML_UNICODE macros. If neither of these is set, then XML_Char contains characters encoding UTF-8. Otherwise you'll be receiving UTF-16 in the form of either unsigned short or wchar_t characters.

Note that you'll receive them in this form independent of the original encoding of the document. Elsewhere in this document, I may make this point by simply referring to UTF-8.


XML_SetElementHandler(XML_Parser p,
                      XML_StartElementHandler start,
                      XML_EndElementHandler end);
typedef void
(*XML_StartElementHandler)(void *userData,
                           const XML_Char *name,
                           const XML_Char **atts);
typedef void
(*XML_EndElementHandler)(void *userData,
                         const XML_Char *name);

Set handlers for start and end tags. Attributes are passed to the start handler as a pointer to a vector of char pointers. Each attribute seen in a start (or empty) tag occupies 2 consecutive places in this vector: the attribute name followed by the attribute value. These pairs are terminated by a null pointer.


XML_SetCharacterDataHandler(XML_Parser p,
                            XML_CharacterDataHandler charhndl)
typedef void
(*XML_CharacterDataHandler)(void *userData,
                            const XML_Char *s,
                            int len);

Set a text handler. The string your handler receives is NOT zero terminated. You have to use the length argument to deal with the end of the string. A single block of contiguous text free of markup may still result in a sequence of calls to this handler. In other words, if you're searching for a pattern in the text, it may be split across calls to this handler.


XML_SetProcessingInstructionHandler(XML_Parser p,
                                    XML_ProcessingInstructionHandler proc)
typedef void
(*XML_ProcessingInstructionHandler)(void *userData,
                                    const XML_Char *target,
                                    const XML_Char *data);

Set a handler for processing instructions. The target is the first word in the processing instruction. The data is the rest of the characters in it after skipping all whitespace after the initial word.


XML_SetCommentHandler (XML_Parser p,
                      XML_CommentHandler cmnt)
typedef void
(*XML_CommentHandler)(void *userData,
                      const XML_Char *data);

Set a handler for comments. The data is all text inside the comment delimiters.


XML_SetCdataSectionHandler(XML_Parser p,
                           XML_StartCdataSectionHandler start,
                           XML_EndCdataSectionHandler end)
typedef void
(*XML_StartCdataSectionHandler)(void *userData);
typedef void
(*XML_EndCdataSectionHandler)(void *userData);

Sets handlers that get called at the beginning and end of a CDATA section.


XML_SetDefaultHandler(XML_Parser p,
                      XML_DefaultHandler hndl)
typedef void
(*XML_DefaultHandler)(void *userData,
                      const XML_Char *s,
                      int len);

Sets a handler for any characters in the document which wouldn't otherwise be handled. This includes both data for which no handlers can be set (like some kinds of DTD declarations) and data which could be reported but which currently has no handler set. Note that a contiguous piece of data that is destined to be reported to the default handler may actually be reported over several calls to the handler. Setting the handler with this call has the side effect of turning off expansion of references to internally defined general entities. Instead these references are passed to the default handler.


XML_SetDefaultHandlerExpand(XML_Parser p,
                            XML_DefaultHandler hndl)

This sets a default handler, but doesn't affect expansion of internal entity references.


XML_SetExternalEntityRefHandler(XML_Parser p,
                                XML_ExternalEntityRefHandler hndl)
typedef int
(*XML_ExternalEntityRefHandler)(XML_Parser parser,
                                const XML_Char *context,
                                const XML_Char *base,
                                const XML_Char *systemId,
                                const XML_Char *publicId);

Set an external entity reference handler. This handler is also called for processing an external DTD subset if parameter entity parsing is in effect. (See XML_SetParamEntityParsing )

The base parameter is the base to use for relative system identifiers. It is set by XML_SetBase and may be null. The public id parameter is the public id given in the entity declaration and may be null. The system id is the system identifier specified in the entity declaration and is never null.

There are a couple of ways in which this handler differs from others. First, this handler returns an integer. A non-zero value should be returned for successful handling of the external entity reference. Returning a zero indicates failure, and causes the calling parser to return an XML_ERROR_EXTERNAL_ENTITY_HANDLING error.

Second, instead of having userData as its first argument, it receives the parser that encountered the entity reference. This, along with the context parameter, may be used as arguments to a call to XML_ExternalEntityParserCreate. Using the returned parser, the body of the external entity can be recursively parsed.

Since this handler may be called recursively, it should not be saving information into global or static variables.


XML_SetUnknownEncodingHandler(XML_Parser p,
                              XML_UnknownEncodingHandler enchandler,
         void *encodingHandlerData)
typedef int
(*XML_UnknownEncodingHandler)(void *encodingHandlerData,
                              const XML_Char *name,
                              XML_Encoding *info);

Set a handler to deal with encodings other than the built in set. If the handler knows how to deal with an encoding with the given name, it should fill in the info data structure and return 1. Otherwise it should return 0.

typedef struct {
  int map[256];
  void *data;
  int (*convert)(void *data, const char *s);
  void (*release)(void *data);
} XML_Encoding;

The map array contains information for every possible possible leading byte in a byte sequence. If the corresponding value is >= 0, then it's a single byte sequence and the byte encodes that Unicode value. If the value is -1, then that byte is invalid as the initial byte in a sequence. If the value is -n, where n is an integer > 1, then n is the number of bytes in the sequence and the actual conversion is accomplished by a call to the function pointed at by convert. This function may return -1 if the sequence itself is invalid. The convert pointer may be null if there are only single byte encodings. The data parameter passed to the convert function is the data pointer from XML_Encoding. The string s is NOT null terminated and points at the sequence of bytes to be converted.

The function pointed at by release is called by the parser when it is finished with the encoding. It may be null.


XML_SetNamespaceDeclHandler(XML_Parser p,
                            XML_StartNamespaceDeclHandler start,
                            XML_EndNamespaceDeclHandler end)
typedef void
(*XML_StartNamespaceDeclHandler)(void *userData,
                                 const XML_Char *prefix,
                                 const XML_Char *uri);
typedef void
(*XML_EndNamespaceDeclHandler)(void *userData,
                               const XML_Char *prefix);

Set handlers for namespace declarations. Namespace declarations occur inside start tags. But the namespace declaration start handler is called before the start tag handler for each namespace declared in that start tag. The corresponding namespace end handler is called after the end tag for the element the namespace is associated with.


XML_SetUnparsedEntityDeclHandler(XML_Parser p,
                                 XML_UnparsedEntityDeclHandler h)
typedef void
(*XML_UnparsedEntityDeclHandler)(void *userData,
                                 const XML_Char *entityName,
                                 const XML_Char *base,
                                 const XML_Char *systemId,
                                 const XML_Char *publicId,
                                 const XML_Char *notationName);

Set a handler that receives declarations of unparsed entities. These are entity declarations that have a notation (NDATA) field:

<!ENTITY logo SYSTEM "images/logo.gif" NDATA gif>

So for this example, the entityName would be "logo", the systemId would be "images/logo.gif" and notationName would be "gif". For this example the publicId parameter is null. The base parameter would be whatever has been set with XML_SetBase. If not set, it would be null.


XML_SetNotationDeclHandler(XML_Parser p,
                           XML_NotationDeclHandler h)
typedef void
(*XML_NotationDeclHandler)(void *userData,
                           const XML_Char *notationName,
                           const XML_Char *base,
                           const XML_Char *systemId,
                           const XML_Char *publicId);

Set a handler that receives notation declarations.


XML_SetNotStandaloneHandler(XML_Parser p,
                            XML_NotStandaloneHandler h)
typedef int 
(*XML_NotStandaloneHandler)(void *userData);

Set a handler that is called if the document is not "standalone". This happens when there is an external subset or a reference to a parameter entity, but does not have standalone set to "yes" in an XML declaration. If this handler returns 0, then the parser will throw an XML_ERROR_NOT_STANDALONE error.

Parse position and error reporting functions

These are the functions you'll want to call when the parse functions return 0, although the position reporting functions are useful outside of errors. The position reported is that of the first of the sequence of characters that generated the current event (or the error that caused the parse functions to return 0.)


enum XML_Error XML_GetErrorCode(XML_Parser p)
Return what type of error has occurred.


const XML_LChar *XML_ErrorString(int code)
Return a string describing the error corresponding to code. The code should be one of the enums that can be returned from XML_GetErrorCode.


long XML_GetCurrentByteIndex(XML_Parser p)
Return the byte offset of the position.


int XML_GetCurrentLineNumber(XML_Parser p)
Return the line number of the position.


int XML_GetCurrentColumnNumber(XML_Parser p)
Return the offset, from the beginning of the current line, of the position.

Miscellaneous functions

The functions in this section either obtain state information from the parser or can be used to dynamically set parser options.


XML_SetUserData(XML_Parser p, void *userData)
This sets the user data pointer that gets passed to handlers.


void * XML_GetUserData(XML_Parser p)
This returns the user data pointer that gets passed to handlers. It is actually implemented as a macro.


void XML_UseParserAsHandlerArg(XML_Parser p)
After this is called, handlers receive the parser in the userData argument. The userData information can still be obtained using the XML_GetUserData function above.


int XML_SetBase(XML_Parser p, const XML_Char *base)
Set the base to be used for resolving relative URIs in system identifiers. The return value is 0 if there's no memory to store base, otherwise it's non-zero.


const XML_Char * XML_GetBase(XML_Parser p)
Return the base for resolving relative URIs.


int XML_GetSpecifiedAttributeCount(XML_Parser p)
When attributes are reported to the start handler in the atts vector, attributes that were explicitly set in the element occur before any attributes that receive their value from default information in an ATTLIST declaration. This function returns the number of attributes that were explicitly set, thus giving the offset of the first attribute set due to defaults. It supplies information for the last call to a start handler. If you're in a start handler, then that means the current call.


int XML_SetEncoding(XML_Parser p, const XML_Char *encoding)
Set the encoding to be used by the parser. It is equivalent to passing a non-null encoding argument to the parser creation functions. It must not be called after XML_Parser or XML_ParseBuffer have been called on the parser.


int XML_SetParamEntityParsing(XML_Parser p, enum XML_ParamEntityParsing code)
If the parser wasn't compiled with the XML_DTD macro set, then this just returns 0. Otherwise it returns 1 and enables parsing of parameter entities, including the external parameter entity that is the external DTD subset, according to code. The choices for code are: