Expat


Next: , Up: (dir)

Expat

This document describes version 2.0.1 of Expat, a C language library for parsing XML documents. It is the underlying XML parser for the open source Mozilla project, Perl's ‘XML::Parser’, Python's ‘xml.parsers.expat’, and other open–source XML parsers.

The bulk of this document was originally commissioned as an article by ‘XML.com’. They graciously allowed Clark Cooper to retain copyright and to distribute it with Expat. This version has been substantially extended to include documentation on features which have been added since the original article was published, and additional information on using the original interface.

This is a Texinfo reformatting of the original documentation from Expat version 2.0.1. The maintainer of this specific version is Marco Maggi marco.maggi-ipsu@poste.it.

Copyright © 1998, 1999, 2000 Thai Open Source Software Center Ltd and Clark Cooper.

Copyright © 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers.

See the appendix “Package License” for the licence notice.

Appendices

Indexes

--- The Detailed Node Listing ---

Overview

Using Expat

Expat reference


Next: , Previous: Top, Up: Top

1 Overview

This document describes version 2.0.1 of Expat, a C language library for parsing XML documents. It is the underlying XML parser for the open source Mozilla project, Perl's ‘XML::Parser’, Python's ‘xml.parsers.expat’, and other open–source XML parsers.

This library is the creation of James Clark, who's also given us groff (an nroff look–alike), Jade (an implemention of ISO's DSSSL stylesheet language for SGML), XP (a Java XML parser package), XT (a Java XSL engine). James was also the technical lead on the XML Working Group at W3C that produced the XML specification.

This is free software, licensed under the MIT/X Consortium license; we can download it from the Expat home page.

http://expat.sourceforge.net/


Next: , Up: overview

1.1 The Expat XML parser

Expat is a stream–oriented parser: We register callback or handler functions and then start feeding the parser with the document; as the parser recognizes parts of the document, it calls the appropriate handler. The document is processed in pieces, so we can start parsing before loading the whole document; this also allows us to parse really huge documents that will not fit in memory.

Expat can be intimidating due to the many kinds of handlers and options we can set. But we only need to learn four functions in order to do 90% of what we'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()
Feed a buffer holding the document to the parser.

Let's look at a very simple example program that only uses three of the above functions since it does not need a character handler. The program prints an element outline, indenting child elements to distinguish them from the parent elements.

     /***********************************************************
      * outline.c
      *
      * Copyright 1999, Clark Cooper
      * All rights reserved.
      *
      * This program is free software; you can redistribute it
      * and/or modify it under the terms of the license contained
      * in the COPYING file that comes with the expat distribution.
      *
      * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
      * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
      * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
      * PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS
      * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
      * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
      * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
      * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      *
      * Read an XML document from standard input and print an
      * element outline on standard output.  Must be used with
      * Expat compiled for UTF-8 output.
      */
     
     
     #include <stdio.h>
     #include <expat.h>
     
     #if defined(__amigaos__) && defined(__USE_INLINE__)
     #  include <proto/expat.h>
     #endif
     
     #ifdef XML_LARGE_SIZE
     #  if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
     #    define XML_FMT_INT_MOD "I64"
     #  else
     #    define XML_FMT_INT_MOD "ll"
     #  endif
     #else
     #  define XML_FMT_INT_MOD "l"
     #endif
     
     #define BUFFSIZE        8192
     
     char Buff[BUFFSIZE];
     
     int Depth;
     
     static void XMLCALL
     start (void *data, const char *element, const char **attribute)
     {
       for (int i = 0; i < Depth; i++)
         printf("  ");
     
       printf("%s", element);
     
       for (int i = 0; attribute[i]; i += 2)
         printf(" %s='%s'", attribute[i], attribute[i + 1]);
     
       printf("\n");
       Depth++;
     }
     
     static void XMLCALL
     end (void *data, const char *el)
     {
       Depth--;
     }
     
     int
     main (int argc, char *argv[])
     {
       XML_Parser p = XML_ParserCreate(NULL);
       if (! p)
         {
           fprintf(stderr, "Couldn't allocate memory for parser\n");
           exit(-1);
         }
     
       XML_SetElementHandler(p, start, end);
     
       for (;;)
         {
           int done;
           int len;
     
           len = (int)fread(Buff, 1, BUFFSIZE, stdin);
           if (ferror(stdin))
             {
               fprintf(stderr, "Read error\n");
               exit(-1);
             }
         done = feof(stdin);
     
         if (XML_Parse(p, Buff, len, done) == XML_STATUS_ERROR)
           {
             fprintf(stderr,
                     "Parse error at line %" XML_FMT_INT_MOD "u:\n%s\n",
                     XML_GetCurrentLineNumber(p),
                     XML_ErrorString(XML_GetErrorCode(p)));
             exit(-1);
           }
     
           if (done)
             break;
         }
       XML_ParserFree(p);
       return 0;
     }

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

Note the ‘XMLCALL’ annotation used for the callbacks. This is used to ensure that the Expat and the callbacks are using the same calling convention in case the compiler options used for Expat itself and the client code are different. Expat tries not to care what the default calling convention is, though it may require that it be compiled with a default convention of ‘cdecl’ on some platforms. For code which uses Expat, however, the calling convention is specified by the ‘XMLCALL’ annotation on most platforms; callbacks should be defined using this annotation.

The ‘XMLCALL’ annotation was added in Expat 1.95.7, but existing working Expat applications don't need to add it (since they are already using the ‘cdecl’ calling convention, or they would not be working). The annotation is only needed if the default calling convention may be something other than ‘cdecl’. To use the annotation safely with older versions of Expat, we can conditionally define it after including Expat's header file:

     #include <expat.h>
     
     #ifndef XMLCALL
     #  if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) &&
           !defined(__CYGWIN__)
     #    define XMLCALL __cdecl
     #  elif defined(__GNUC__)
     #    define XMLCALL __attribute__((cdecl))
     #  else
     #    define XMLCALL
     #  endif
     #endif


Previous: overview intro, Up: overview

1.2 Building and installing Expat

The Expat distribution comes as a compressed tar file; we may download the latest version from Source Forge. After unpacking it, change the current directory to the top of the source tree, then follow either the Win32 directions or Unix directions below.

Building under Win32

If we're using the GNU compiler under Cygwin, follow the Unix directions in the next section. Otherwise if we have Microsoft's Developer Studio installed, then from Windows Explorer double–click on expat.dsp in the lib directory and build and install in the usual manner.

Alternatively, we may download the Win32 binary package that contains the expat.h include file and a pre–built DLL.

Building under Unix (or GNU)

First we'll need to run the configure shell script in order to configure the Makefiles and headers for our system.

If we're happy with all the defaults that configure picks for us, and we have permission on our system to install into /usr/local, we can install Expat with this sequence of commands:

     $ ./configure
     $ make
     $ make install

There are some options that we can provide to this script, but the only one we'll mention here is the --prefix option. We can find out all the options available by running configure with just the --help option.

By default, the configure script sets things up so that the library gets installed in /usr/local/lib and the associated header file in /usr/local/include. But if we were to give the option --prefix=/home/me/mystuff, then the library and header would get installed in /home/me/mystuff/lib and /home/me/mystuff/include respectively.

Configuring Expat Using the Pre–Processor

Expat's feature set can be configured using a small number of pre-processor definitions. The definition of this symbols does not affect the set of entry points for Expat, only the behavior of the API and the definition of character types in the case of XML_UNICODE_WCHAR_T. The symbols are:

XML_DTD
Include support for using and reporting DTD–based content. If this is defined, default attribute values from an external DTD subset are reported and attribute value normalization occurs based on the type of attributes defined in the external subset. Without this, Expat has a smaller memory footprint and can be faster, but will not load external entities or process conditional sections. This does not affect the set of functions available in the API.
XML_NS
When defined, support for the Namespaces in XML specification is included.
XML_UNICODE
When defined, character data reported to the application is encoded in UTF-16 using wide characters of the type XML_Char. This is implied if XML_UNICODE_WCHAR_T is defined.
XML_UNICODE_WCHAR_T
If defined, causes the XML_Char character type to be defined using the wchar_t type; otherwise, unsigned short is used. Defining this implies XML_UNICODE.
XML_LARGE_SIZE
If defined, causes the XML_Size and XML_Index integer types to be at least 64 bits in size. This is intended to support processing of very large input streams, where the return values of XML_GetCurrentByteIndex(), XML_GetCurrentLineNumber() and XML_GetCurrentColumnNumber() could overflow. It may not be supported by all compilers, and is turned off by default.
XML_CONTEXT_BYTES
The number of input bytes of markup context which the parser will ensure are available for reporting via XML_GetInputContext(). This is normally set to 1024, and must be set to a positive interger. If this is not defined, the input context will not be available and XML_GetInputContext() will always report NULL. Without this, Expat has a smaller memory footprint and can be faster.
XML_STATIC
On Windows, this should be set if Expat is going to be linked statically with the code that calls it; this is required to get all the right MSVC magic annotations correct. This is ignored on other platforms.


Next: , Previous: overview, Up: Top

2 Using Expat


Next: , Up: using

2.1 Compiling and linking against Expat

Unless Expat is installed in a location not expected by the compiler and linker, all we have to do to use Expat programs is to include the Expat header:

     #include <expat.h>

in the source files that make calls to it and to tell the linker that it needs to link against the Expat library. On Unix systems, this would usually be done with the -lexpat argument. Otherwise, we'll need to tell the compiler where to look for the Expat header, and to the linker where to find the Expat library. We may also need to take steps to tell the operating system where to find this library at run time.

On a Unix–based system, here's what a Makefile might look like when Expat is installed in a standard location:

     CC=cc
     LDFLAGS=
     LIBS= -lexpat
     xmlapp: xmlapp.o
             $(CC) $(LDFLAGS) -o xmlapp xmlapp.o $(LIBS)

If we installed Expat in, say, /home/me/mystuff, then the Makefile would look like this:

     CC=cc
     CFLAGS= -I/home/me/mystuff/include
     LDFLAGS=
     LIBS= -L/home/me/mystuff/lib -lexpat
     xmlapp: xmlapp.o
             $(CC) $(LDFLAGS) -o xmlapp xmlapp.o $(LIBS)

We'd also have to set the environment variable LD_LIBRARY_PATH to /home/me/mystuff/lib (or to ${LD_LIBRARY_PATH}:/home/me/mystuff/lib if LD_LIBRARY_PATH already has some directories in it) in order to run the program.


Next: , Previous: using compile, Up: using

2.2 Basics

As we saw in the example in the overview, the first step in parsing an XML document with Expat is to create a parser object. There are three functions in the Expat API for creating a parser object. However, only two of these (XML_ParserCreate() and XML_ParserCreateNS()) can be used for constructing a parser for a top–level document. The object returned by these functions is an opaque pointer to data with further internal structure (expat.h declares it as void *). In order to free the memory associated with this object we must call XML_ParserFree().

Note that if we have provided any user data that gets stored in the parser, then our application is responsible for freeing it prior to calling XML_ParserFree().

The objects returned by the parser creation functions are good for parsing only one XML document or external parsed entity. If the application needs to parse many XML documents, then it needs to create a parser object for each one. The best way to deal with this is to create a higher level object containing all the default initialization we want for the parser objects.

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 we're likely to want to keep on a stack are the currently opened element and it's attributes. We push this information onto the stack in the start handler and we 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 we had one). The outline program shown in the overview presents one example. Another such task would be skipping over a complete element. When we see the start tag for the element we want to skip, we 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 we follow the convention that the root element starts at 1, then we 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 */
     }
     
     void XMLCALL
     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++;
     }
     
     void XMLCALL
     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;
     }

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.


Next: , Previous: using basics, Up: using

2.3 Communicating between handlers

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

In the reference section, an argument to a callback function is named userData and have type ‘void *’ if the user data is passed; it will have the type ‘XML_Parser’ if the parser itself is passed. When the parser is passed, the user data may be retrieved using XML_GetUserData().

One common case where multiple calls to a single handler may need to communicate using an application data structure, is the case when content passed to the character data handler (set by XML_SetCharacterDataHandler()) needs to be accumulated.

A common first–time mistake with any of the event–oriented interfaces to an XML parser is to expect all the text contained in an element to be reported by a single call to the character data handler. Expat, like many other XML parsers, reports such data as a sequence of calls; there's no way to know when the end of the sequence is reached until a different callback is made. A buffer referenced by the user data structure proves both an effective and convenient place to accumulate character data.


Next: , Previous: using comm, Up: using

2.4 XML version

Expat is an XML 1.0 parser, and as such never complains based on the value of the version pseudo–attribute in the XML declaration, if present.

If an application needs to check the version number (to support alternate processing), it should use the XML_SetXmlDeclHandler() function to set a handler that uses the information in the XML declaration to determine what to do. This example shows how to check that only a version number of ‘1.0’ is accepted:

     static int wrong_version;
     static XML_Parser parser;
     
     static void XMLCALL
     xmldecl_handler(void            *userData,
                     const XML_Char  *version,
                     const XML_Char  *encoding,
                     int              standalone)
     {
       static const XML_Char Version_1_0[] = { '1', '.', '0', 0 };
     
       int i;
     
       for (i=0; i<(sizeof(Version_1_0) / sizeof(Version_1_0[0])); ++i)
         {
           if (version[i] != Version_1_0[i])
             {
               wrong_version = 1;
               /* also clear all other handlers: */
               XML_SetCharacterDataHandler(parser, NULL);
               ...
               return;
             }
         }
       ...
     }


Next: , Previous: using version, Up: using

2.5 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 the start handler will not see these attributes. The 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. By default 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 not well–formed when namespace processing is enabled, and will trigger an error. Unprefixed attribute names are never expanded, and unprefixed element names are only expanded when they are in the scope of a default namespace.

However if XML_SetReturnNSTriplet() has been called with a non–zero do_nst parameter, then the expanded form for names with an explicit prefix is a concatenation of: URI, separator, local name, separator, prefix.

We 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 XML_StartNamespaceDeclHandler is called prior to the start tag handler and the XML_EndNamespaceDeclHandler is called after 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 XML_StartNamespaceDeclHandler would be called three times before the start tag handler is called, once for each declaration.


Next: , Previous: using namespace, Up: using

2.6 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, we 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 XML_UnknownEncodingHandler. This handler gets passed the encoding name and a pointer to an XML_Encoding data structure. Our handler must fill in this structure and return XML_STATUS_OK if it knows how to deal with the encoding. Otherwise the handler should return XML_STATUS_ERROR. The handler also gets passed a pointer to an optional application data structure that we may indicate when we set the handler.

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

  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 first 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 or UTF-16 (depending on how Expat was compiled). Our application is responsible for any translation of these strings into other encodings.


Next: , Previous: using encodings, Up: using

2.7 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 we've set no XML_ExternalEntityRefHandler, then external entity references are silently ignored. Otherwise, it calls our handler with the information needed to read and parse the external entity.

Our 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. We may then use XML_Parse() or XML_ParseBuffer() calls against this parser. Since external entities may refer to other external entities, our handler should be prepared to be called recursively.


Next: , Previous: using entity, Up: using

2.8 Parsing DTDs

In order to parse parameter entities, before starting the parse, we 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 DTD, we also have to set an external entity reference handler as described in using entity.


Previous: using dtd, Up: using

2.9 Temporarily stopping parsing

Expat 1.95.8 introduces a new feature: It is now possible to stop parsing temporarily from within a handler function, even if more data has already been passed into the parser. Applications for this include:

To take advantage of this feature, the main parsing loop of an application needs to support this specifically. It cannot be supported with a parsing loop compatible with Expat 1.95.7 or earlier (though existing loops will continue to work without supporting the stop/resume feature).

An application that uses this feature for a single parser will have the rough structure (in pseudo–code):

     fd = open_input()
     p  = create_parser()
     
     if parse_xml(p, fd)
       {
         /* suspended */
     
         int suspended = 1;
     
         while (suspended)
           {
             do_something_else()
             if ready_to_resume()
               {
                 suspended = continue_parsing(p, fd);
               }
           }
       }

An application that may resume any of several parsers based on input (either from the XML being parsed or some other source) will certainly have more interesting control structures.

This C function could be used for the parse_xml() function mentioned in the pseudo-code above:

     #define BUFF_SIZE 10240
     
     /* Parse a document from the open file descriptor 'fd' until
        the parse is complete (the document has been completely
        parsed, or there's been an error), or the parse is stopped.
        Return non-zero when the parse is merely suspended. */
     
     int
     parse_xml (XML_Parser p, int fd)
     {
       for (;;)
         {
           int last_chunk;
           int bytes_read;
           enum XML_Status status;
     
           void *buff = XML_GetBuffer(p, BUFF_SIZE);
           if (buff == NULL)
             {
              /* handle error... */
              return 0;
             }
         bytes_read = read(fd, buff, BUFF_SIZE);
         if (bytes_read < 0)
           {
             /* handle error... */
             return 0;
           }
         status = XML_ParseBuffer(p, bytes_read, bytes_read == 0);
         switch (status)
           {
             case XML_STATUS_ERROR:
               /* handle error... */
               return 0;
             case XML_STATUS_SUSPENDED:
               return 1;
           }
           if (bytes_read == 0)
             return 0;
         }
     }

The corresponding continue_parsing() function is somewhat simpler, since it only need deal with the return code from XML_ResumeParser(); it can delegate the input handling to the parse_xml() function:

     /* Continue parsing a document which had been suspended.
        The 'p' and 'fd' arguments are the same as passed to
        parse_xml().  Return non-zero when the parse is
        suspended. */
     int
     continue_parsing (XML_Parser p, int fd)
     {
       enum XML_Status status = XML_ResumeParser(p);
       switch (status)
         {
           case XML_STATUS_ERROR:
             /* handle error... */
             return 0;
           case XML_ERROR_NOT_SUSPENDED:
             /* handle error... */
             return 0;.
           case XML_STATUS_SUSPENDED:
             return 1;
         }
       return parse_xml(p, fd);
     }

Now that we've seen what a mess the top–level parsing loop can become, what have we gained? Very simply, we can now use the XML_StopParser() function to stop parsing, without having to go to great lengths to avoid additional processing that we're expecting to ignore. As a bonus, we get to stop parsing temporarily, and come back to it when we're ready.

To stop parsing from a handler function, use the XML_StopParser() function. This function takes two arguments; the parser being stopped and a flag indicating whether the parse can be resumed in the future.


Next: , Previous: using, Up: Top

3 Expat reference


Next: , Up: api

3.1 Error codes

— Enumeration: XML_Status

Constants used as return values to indicate success or failure.

— Enumerated Constant: XML_STATUS_ERROR
— Enumerated Constant: XML_STATUS_OK
— Enumerated Constant: XML_STATUS_SUSPENDED

Constants of type enum XML_Status.

— Enumeration: XML_Error

Constants used to specify an error type.

— Enumerated Constant: XML_ERROR_NONE

Constant of type enum XML_Status. No error.

— Enumerated Constant: XML_ERROR_NO_MEMORY

Constant of type enum XML_Status. Out of memory.

— Enumerated Constant: XML_ERROR_SYNTAX

Constant of type enum XML_Status. Syntax error.

— Enumerated Constant: XML_ERROR_NO_ELEMENTS

Constant of type enum XML_Status. No element found.

— Enumerated Constant: XML_ERROR_INVALID_TOKEN

Constant of type enum XML_Status. Document not well–formed (invalid token).

— Enumerated Constant: XML_ERROR_UNCLOSED_TOKEN

Constant of type enum XML_Status. Unclosed token.

— Enumerated Constant: XML_ERROR_PARTIAL_CHAR

Constant of type enum XML_Status. Partial character.

— Enumerated Constant: XML_ERROR_TAG_MISMATCH

Constant of type enum XML_Status. Mismatched tag.

— Enumerated Constant: XML_ERROR_DUPLICATE_ATTRIBUTE

Constant of type enum XML_Status. Duplicate attribute.

— Enumerated Constant: XML_ERROR_JUNK_AFTER_DOC_ELEMENT

Constant of type enum XML_Status. Junk after document element.

— Enumerated Constant: XML_ERROR_PARAM_ENTITY_REF

Constant of type enum XML_Status. Illegal parameter entity reference.

— Enumerated Constant: XML_ERROR_UNDEFINED_ENTITY

Constant of type enum XML_Status. Undefined entity.

— Enumerated Constant: XML_ERROR_RECURSIVE_ENTITY_REF

Constant of type enum XML_Status. Recursive entity reference.

— Enumerated Constant: XML_ERROR_ASYNC_ENTITY

Constant of type enum XML_Status. Asynchronous entity.

— Enumerated Constant: XML_ERROR_BAD_CHAR_REF

Constant of type enum XML_Status. Reference to invalid character number.

— Enumerated Constant: XML_ERROR_BINARY_ENTITY_REF

Constant of type enum XML_Status. Reference to binary entity.

— Enumerated Constant: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

Constant of type enum XML_Status. Reference to external entity in attribute.

— Enumerated Constant: XML_ERROR_MISPLACED_XML_PI

Constant of type enum XML_Status. XML or text declaration not at start of entity.

— Enumerated Constant: XML_ERROR_UNKNOWN_ENCODING

Constant of type enum XML_Status. Unknown encoding.

— Enumerated Constant: XML_ERROR_INCORRECT_ENCODING

Constant of type enum XML_Status. Encoding specified in XML declaration is incorrect.

— Enumerated Constant: XML_ERROR_UNCLOSED_CDATA_SECTION

Constant of type enum XML_Status. Unclosed CDATA section.

— Enumerated Constant: XML_ERROR_EXTERNAL_ENTITY_HANDLING

Constant of type enum XML_Status. Error in processing external entity reference.

— Enumerated Constant: XML_ERROR_NOT_STANDALONE

Constant of type enum XML_Status. Document is not standalone.

— Enumerated Constant: XML_ERROR_UNEXPECTED_STATE

Constant of type enum XML_Status. Unexpected parser state (send a bug report).

— Enumerated Constant: XML_ERROR_ENTITY_DECLARED_IN_PE

Constant of type enum XML_Status. Entity declared in parameter entity.

— Enumerated Constant: XML_ERROR_FEATURE_REQUIRES_XML_DTD

Constant of type enum XML_Status. Requested feature requires XML_DTD support in Expat.

— Enumerated Constant: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING

Constant of type enum XML_Status. Cannot change setting once parsing has begun.

— Enumerated Constant: XML_ERROR_UNBOUND_PREFIX

Constant of type enum XML_Status. Unbound prefix.

— Enumerated Constant: XML_ERROR_UNDECLARING_PREFIX

Constant of type enum XML_Status. Must not undeclare prefix.

— Enumerated Constant: XML_ERROR_INCOMPLETE_PE

Constant of type enum XML_Status. Incomplete markup in parameter entity.

— Enumerated Constant: XML_ERROR_XML_DECL

Constant of type enum XML_Status. XML declaration not well–formed.

— Enumerated Constant: XML_ERROR_TEXT_DECL

Constant of type enum XML_Status. Text declaration not well–formed.

— Enumerated Constant: XML_ERROR_PUBLICID

Constant of type enum XML_Status. Illegal character(s) in public identifier.

— Enumerated Constant: XML_ERROR_SUSPENDED

Constant of type enum XML_Status. Parser suspended.

— Enumerated Constant: XML_ERROR_NOT_SUSPENDED

Constant of type enum XML_Status. Parser not suspended.

— Enumerated Constant: XML_ERROR_ABORTED

Constant of type enum XML_Status. Parsing aborted.

— Enumerated Constant: XML_ERROR_FINISHED

Constant of type enum XML_Status. Parsing finished.

— Enumerated Constant: XML_ERROR_SUSPEND_PE

Constant of type enum XML_Status. Cannot suspend in external parameter entity.

— Enumerated Constant: XML_ERROR_RESERVED_PREFIX_XML

Constant of type enum XML_Status. Reserved prefix xml must not be undeclared or bound to another namespace name.

— Enumerated Constant: XML_ERROR_RESERVED_PREFIX_XMLNS

Constant of type enum XML_Status. Reserved prefix xmlns must not be declared or undeclared

— Enumerated Constant: XML_ERROR_RESERVED_NAMESPACE_UR

Constant of type enum XML_Status. Prefix must not be bound to one of the reserved namespace names.


Next: , Previous: api errors, Up: api

3.2 Parser creation

— Function: 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:

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

Any other value will invoke XML_UnknownEncodingHandler.

— Function: XML_Parser XML_ParserCreateNS (const XML_Char * encoding, XML_Char sep)

Construct 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 we should pick a character for sep that can't be part of a legal URI. There is a special case when sep is the null character \0: the namespace URI and the local part will be concatenated without any separator—this is intended to support RDF processors. It is a programming error to use the null separator with namespace triplets.

— Function: XML_Parser XML_ParserCreate_MM (const XML_Char * encoding, const XML_Memory_Handling_Suite * ms, const XML_Char * sep)

Construct a new parser using the suite of memory handling functions specified in ms. If ms is NULL, then use the standard set of memory management functions. If sep is non–NULL, then namespace processing is enabled in the created parser and the character pointed at by sep is used as the separator between the namespace URI and the local part of the name.

          typedef struct {
            void * ( *malloc_fcn  )(size_t size);
            void * ( *realloc_fcn )(void *ptr, size_t size);
            void   ( *free_fcn    )(void *ptr);
          } XML_Memory_Handling_Suite;
— Function: void XML_ParserFree (XML_Parser p)

Free memory used by the parser. Our application is responsible for freeing any memory associated with user data.

— Function: XML_Bool XML_ParserReset (XML_Parser p, const XML_Char * encoding)

Clean up the memory structures maintained by the parser so that it may be used again. After this has been called, the parser is ready to start parsing a new document. All handlers are cleared from the parser, except for the unknownEncodingHandler. The parser's external state is re–initialized except for the values of ns and ns_triplets. This function may not be used on a parser created using XML_ExternalEntityParserCreate(); it will return XML_FALSE in that case. Returns XML_TRUE on success. Our application is responsible for dealing with any memory associated with user data.


Next: , Previous: api create, Up: api

3.3 Parsing

To state the obvious: the three parsing functions XML_Parse(), XML_ParseBuffer() and XML_GetBuffer() must not be called from within a handler unless they operate on a separate parser instance, that is: one that did not call the handler. For example, it is fine to call the parsing functions from within an XML_ExternalEntityRefHandler(), if they apply to the parser created by XML_ExternalEntityParserCreate().

NOTE The len argument passed to these functions should be considerably less than the maximum value for an integer, as it could create an integer overflow situation if the added lengths of a buffer and the unprocessed portion of the previous buffer exceed the maximum integer value. Input data at the end of a buffer will remain unprocessed if it is part of an XML token for which the end is not part of that buffer.
— Enumeration: enum XML_Status

Type of the return values.

XML_STATUS_ERROR
Error.
XML_STATUS_OK
Success.

— Function: enum XML_Status 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 zero terminated.

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 successful return XML_STATUS_OK, otherwise XML_STATUS_ERROR.

— Function: enum XML_Status 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.

— Function: void * XML_GetBuffer (XML_Parser p, int len)

Obtain a buffer of size len to read a piece of the document into. Return NULL if Expat can't allocate enough memory for this buffer.

This function has to be called prior to every call to XML_ParseBuffer().

A typical use would look like this:

          #undef BUFF_SIZE
          #define BUFF_SIZE       4096
          XML_Parser       parser = the_parser;
          int              docfd  = the_file_descriptor;
          int              nbytes;
          void *           buff;
          enum XML_Status  status;
          
          for (;;) {
            buff = XML_GetBuffer(parser, BUFF_SIZE);
            if (buff == NULL) {
              /* handle error */
            }
          
            nbytes = read(docfd, buff, BUFF_SIZE);
            if (nbytes < 0) {
              /* handle error */
            }
          
            status = XML_ParseBuffer(parser, nbytes, (0 == nbytes));
            if (XML_STATUS_OK != status) {
              /* handle parse error */
            }
          
            if (0 == nbytes)
              break;
          }
— Function: enum XML_Status XML_StopParser (XML_Parser p, XML_Bool resumable)

Stop parsing causing XML_Parse() or XML_ParseBuffer() to return. Must be called from within a callback handler, except when aborting (when resumable is XML_FALSE) an already suspended parser. Some call–backs may still follow because they would otherwise get lost, including:

and possibly others.

This can be called from most handlers, including DTD related call–backs, except when parsing an external parameter entity and resumable is XML_TRUE.

If successful return XML_STATUS_OK, otherwise XML_STATUS_ERROR. The possible error codes are:

XML_ERROR_SUSPENDED
When suspending an already suspended parser.
XML_ERROR_FINISHED
When the parser has already finished.
XML_ERROR_SUSPEND_PE
When suspending while parsing an external parameter entity.

Since the stop/resume feature requires application support in the outer parsing loop, it is an error to call this function for a parser not being handled appropriately. using stop for details.

When resumable is XML_TRUE then parsing is suspended, that is, XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer() return XML_STATUS_ERROR with error code XML_ERROR_ABORTED.

NOTE This will be applied to the current parser instance only, that is, if there is a parent parser then it will continue parsing when the external entity reference handler returns. It is up to the implementation of that handler to call XML_StopParser() on the parent parser (recursively), if one wants to stop parsing altogether.

When suspended, parsing can be resumed by calling XML_ResumeParser().

NOTE New in Expat 1.95.8.

— Function: enum XML_Status XML_ResumeParser (XML_Parser p)

Resume parsing after it has been suspended with XML_StopParser(). Must not be called from within a handler callback. Return the same status codes of XML_Parse() or XML_ParseBuffer().

An additional error code, XML_ERROR_NOT_SUSPENDED, will be returned if the parser was not currently suspended.

NOTE This must be called on the most deeply nested child parser instance first, and on its parent parser only after the child parser has finished, to be applied recursively until the document entity's parser is restarted. That is, the parent parser will not resume by itself and it is up to the application to call XML_ResumeParser() on it at the appropriate moment.
NOTE New in Expat 1.95.8.

— Enumeration: enum XML_Parsing

Parser status values. Defined symbols are:

          XML_INITIALIZED
          XML_PARSING
          XML_FINISHED
          XML_SUSPENDED
— Struct Typedef: XML_ParsingStatus

The status of a parser. The description of public fields follows.

enum XML_Parsing parsing
The current status of the parser.
XML_Bool finalBuffer
True if the internal buffer holds the final chunk of the document.

— Function: void XML_GetParsingStatus (XML_Parser p, XML_ParsingStatus * status)

Fill the structure referenced by status with the status of the parser with respect to being initialized, parsing, finished, or suspended, and whether the final buffer is being processed.

status must not be NULL.

NOTE New in Expat 1.95.8.


Next: , Previous: api parse, Up: api

3.4 External entities parsers

— Function: 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 XML_ExternalEntityRefHandler. Other state information such as handlers, user data, namespace processing is inherited from the parser passed as the first argument. So we shouldn't need to call any of the behavior changing functions on this parser (unless we want it to act differently than the parent parser).

— Function Pointer Typedef: XML_ExternalEntityRefHandler

External entity reference handler. Defined as:

          typedef int (* XML_ExternalEntityRefHandler)
             (XML_Parser          parser,
              const XML_Char *    context,
              const XML_Char *    base,
              const XML_Char *    system_id,
              const XML_Char *    public_id);

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

The context parameter specifies the parsing context in the format expected by the context argument to XML_ExternalEntityParserCreate(). context is valid only until the handler returns, so if the referenced entity is to be parsed later, it must be copied.

context is NULL only when the entity is a parameter entity, which is how one can differentiate between general and parameter entities.

base is the base to use for relative system identifiers; it is set by XML_SetBase() and may be NULL.

public_id is the public id given in the entity declaration and may be NULL.

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.

  1. This handler returns a status indicator (an integer). XML_STATUS_OK should be returned for successful handling of the external entity reference. Returning XML_STATUS_ERROR indicates failure, and causes the calling parser to return an XML_ERROR_EXTERNAL_ENTITY_HANDLING error.
  2. Instead of having the user data 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.

— Function: void XML_SetExternalEntityRefHandler (XML_Parser p, XML_ExternalEntityRefHandler h)

Set an external entity reference handler.

— Function: void XML_SetExternalEntityRefHandlerArg (XML_Parser P, void * arg)

Set the argument passed to the XML_ExternalEntityRefHandler. If arg is not NULL, it is the new value passed to the handler set using XML_SetExternalEntityRefHandler(); if arg is NULL, the argument passed to the handler function will be the parser object itself.

NOTE The type of arg and the type of the first argument to the XML_ExternalEntityRefHandler do not match. This function takes a void * to be passed to the handler, while the handler accepts an XML_Parser.

This is a historical accident, but will not be corrected before Expat 2.0 (at the earliest) to avoid causing compiler warnings for code that's known to work with this API. It is the responsibility of the application code to know the actual type of the argument passed to the handler and to manage it properly.


Next: , Previous: api external, Up: api

3.5 Setting the handlers


Next: , Up: api handlers

3.5.1 Introductive notes on handlers

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, our 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. Most of the handler setting functions have no return value, an exception is XML_ExternalEntityRefHandler.

Handlers receive strings in arrays of type XML_Char; this type is conditionally defined in expat.h as either char, wchar_t or unsigned short. The former implies UTF-8 encoding, the latter two imply UTF-16 encoding. Note that the handler will receive them in this form independently from the original encoding of the document.


Next: , Previous: api handlers intro, Up: api handlers

3.5.2 XML declaration handler

XML declarations look like this:

     <?xml version='1.0'?>
     <?xml version='1.0'? encoding='utf-8'>
     <?xml version='1.0'? standalone='yes'>
     <?xml version='1.0'? standalone='no'>
— Function Pointer Typedef: XML_XmlDeclHandler

Handler for XML declarations and also for text declarations discovered in external entities. Defined as:

          typedef void (* XML_XmlDeclHandler)
            (void           *     user_data,
             const XML_Char *     version,
             const XML_Char *     encoding,
             int                  standalone);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

version is either NULL or references a zero–terminated string representing the XML specification version; such string is always 1.0. The way to distinguish the kind of input is that version will be NULL for text declarations.

encoding is either NULL or references a zero–terminated string representing the character encoding of the document being parsed.

standalone will be:

-1
Indicating that there was no standalone parameter in the declaration.
0
Indicating that standalone was given as no.
+1
Indicating that standalone was given as yes.

— Function: void XML_SetXmlDeclHandler (XML_Parser p, XML_XmlDeclHandler xmldecl)

Set a handler that is called for XML declarations and also for text declarations discovered in external entities.


Next: , Previous: api handlers xml decl, Up: api handlers

3.5.3 Non–standalone handler

— Function Pointer Typedef: XML_NotStandaloneHandler

Handler called if the document is not “standalone”. Defined as:

          typedef int (* XML_NotStandaloneHandler) (void * user_data);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

This handler is called when there is an external subset or a reference to a parameter entity, but it does not have standalone set to yes in an XML declaration.

If this handler returns XML_STATUS_ERROR: the parser will throw an XML_ERROR_NOT_STANDALONE error.

— Function: void XML_SetNotStandaloneHandler (XML_Parser p, XML_NotStandaloneHandler h)

Set a handler that is called if the document is not “standalone”.


Next: , Previous: api handlers standalone, Up: api handlers

3.5.4 DTD document type declaration

An internal document type declaration looks like this:

     <!DOCTYPE ball [
       <!ELEMENT ball EMPTY>
       <!ATTLIST ball colour CDATA #REQUIRED>
     ]>

external document type declarations look like this:

     <!DOCTYPE toys SYSTEM 'http://localhost/toys'>
     <!DOCTYPE toys PUBLIC 'The Toys' 'http://localhost/toys'>

with the URI http://localhost/toys being the system identifier and The Toys being the public identifier. SYSTEM document types are meant for use by a single author or group of authors; PUBLIC document types are meant for public use.

— Function Pointer Typedef: XML_StartDoctypeDeclHandler

Handler called at the start of a <!DOCTYPE declaration, before any external or internal subset is parsed. Defined as:

          typedef void (* XML_StartDoctypeDeclHandler)
             (void           *    user_data,
              const XML_Char *    doctype_name,
              const XML_Char *    system_id,
              const XML_Char *    public_id,
              int                 has_internal_subset);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

doctype_name references a zero–terminated string representing the document type name.

system_id either is NULL or references a zero–terminated string representing the system identifier.

public_id either is NULL or references a zero–terminated string representing the public identifier.

has_internal_subset will be non–zero if the <!DOCTYPE declaration has an internal subset.

— Function: void XML_SetStartDoctypeDeclHandler (XML_Parser P, XML_StartDoctypeDeclHandler H)

Set a handler called at the start of a <!DOCTYPE declaration, before any external or internal subset is parsed.

— Function Pointer Typedef: XML_EndDoctypeDeclHandler

Handler called at the end of a <!DOCTYPE declaration, after parsing any external subset. Defined as:

          typedef void (* XML_EndDoctypeDeclHandler) (void * user_data);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

— Function: void XML_SetEndDoctypeDeclHandler (XML_Parser P, XML_EndDoctypeDeclHandler H)

Set a handler that is called at the end of a <!DOCTYPE declaration, after parsing any external subset.

— Function: void XML_SetDoctypeDeclHandler (XML_Parser P, XML_StartDoctypeDeclHandler S, XML_EndDoctypeDeclHandler E)

Set both <!DOCTYPE handlers with one call.


Next: , Previous: api handlers dtd doctype, Up: api handlers

3.5.5 Element DTD declaration handlers

To declare the following XML fragment in a DTD:

     <numbers><one/><two/><three/></numbers>

we do:

     <!ELEMENT one     EMPTY>
     <!ELEMENT two     EMPTY>
     <!ELEMENT three   EMPTY>
     <!ELEMENT numbers (one,two,three)>

when Expat parses the last declaration of this DTD fragment: numbers is the “root element” and the others are its “children”.

— Function Pointer Typedef: XML_ElementDeclHandler

Handler for element declarations in the DTD; invoked whenever, while processing a DTD, the parser finds an <!ELEMENT token. Defined as:

          typedef void (* XML_ElementDeclHandler)
            (void *               user_data,
             const XML_Char *     name,
             XML_Content *        model);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

name references a zero–terminated string holding the name of the element being declared; this pointer is never NULL.

model references a structure describing the element declaration, this pointer is never NULL; it is the application's responsibility to free this data structure using XML_FreeContentModel().

— Function: void XML_SetElementDeclHandler (XML_Parser p, XML_ElementDeclHandler H)

Set or unset a handler for element DTD declarations.

— Function: void XML_FreeContentModel (XML_Parser p, XML_Content * model)

Deallocate the model argument passed to the XML_ElementDeclHandler handler. This function should not be used for any other purpose.

— Enumeration: XML_Content_Type

Used to identify the content type in an element's DTD declaration.

— Enumeration Constant: XML_CTYPE_EMPTY
— Enumeration Constant: XML_CTYPE_ANY
— Enumeration Constant: XML_CTYPE_MIXED
— Enumeration Constant: XML_CTYPE_NAME
— Enumeration Constant: XML_CTYPE_CHOICE
— Enumeration Constant: XML_CTYPE_SEQ

Values of the XML_Content_Type enumeration. See the description of the field type in the structure XML_Content for details.

— Enumeration: XML_Content_Quant

Specify the quantifier used in an element's DTD declaration.

— Enumeration Constant: XML_CQUANT_NONE
— Enumeration Constant: XML_CQUANT_OPT
— Enumeration Constant: XML_CQUANT_REP
— Enumeration Constant: XML_CQUANT_PLUS

Values of the XML_Content_Quant enumeration. An element declaration is described by the values as follows:

XML_CQUANT_NONE
When there is no quantifier.
XML_CQUANT_OPT
When the quantifier ? is used.
XML_CQUANT_REP
When the quantifier * is used. We can imagine REP to stand for “replicated”.
XML_CQUANT_PLUS
When the quantifier + is used.

— Struct Typedef: XML_Content

Instances of this structure type can be: “root elements” when this structure represents an <!ELEMENT declaration; “children elements” when this structure is an element of an array referenced by the children field (see below). Description of public fields follows.

enum XML_Content_Type type
The type of the element described by this instance. When this instance represents a root element, the value is as follows:
               <!ELEMENT THIS EMPTY>
                 ⇒ type == XML_CTYPE_EMPTY
               
               <!ELEMENT THIS ANY>
                 ⇒ type == XML_CTYPE_ANY
               
               <!ELEMENT THIS (#PCDATA)>
                 ⇒ type == XML_CTYPE_MIXED
               
               <!ELEMENT THIS (#PCDATA|THAT)*>
                 ⇒ type == XML_CTYPE_MIXED
               
               <!ELEMENT THIS (THAT|THOSE)>
                 ⇒ type == XML_CTYPE_CHOICE
               
               <!ELEMENT THIS (THAT, THOSE)>
                 ⇒ type == XML_CTYPE_SEQ

when this instance represents a child element, the value of this field is always XML_CTYPE_NAME.

If the type is EMPTY or ANY: quant is XML_CQUANT_NONE and the other fields are zero or NULL.

If the type is MIXED: quant is XML_CQUANT_NONE or XML_CQUANT_REP.

enum XML_Content_Quant quant
The quantifier for the element's content. If this structure represents a root element, the value is as follows:
               <!ELEMENT this (that)>
                 ⇒ quant == XML_CQUANT_NONE
               
               <!ELEMENT this (that)?>
                 ⇒ quant == XML_CQUANT_OPT
               
               <!ELEMENT this (that)*>
                 ⇒ quant == XML_CQUANT_REP
               
               <!ELEMENT this (that)+>
                 ⇒ quant == XML_CQUANT_PLUS

if this structure represents a child element the value is always XML_CQUANT_NONE.

const XML_Char * name
NULL for root elements; for children elements: references a zero–terminated string representing the child's element name.
XML_Content * children
unsigned int numchildren
children is NULL or a pointer to an array of structures describing the children elements; the number of elements in the array is numchildren.

One of the following cases is possible:

  • When type is XML_CTYPE_EMPTY or XML_CTYPE_ANY: the array is empty.
  • When type is XML_CTYPE_CHOICE or XML_CTYPE_SEQ: the array has a number of entries equal to the number of children elements.
  • When type is XML_CTYPE_MIXED and the element's content specification is (#PCDATA): the array is empty.
  • When type is XML_CTYPE_MIXED and the element's content specification lists children elements: the array has a number of entries equal to the number of children elements.


Next: , Previous: api handlers dtd element, Up: api handlers

3.5.6 Attribute list DTD declaration handlers

— Function Pointer Typedef: XML_AttlistDeclHandler

Handler for attribute list declarations in the DTD; invoked whenever, while processing a DTD, the parser finds an <!ATTLIST token. Defined as:

          typedef void (* XML_AttlistDeclHandler)
            (void *               user_data,
             const XML_Char *     element_name,
             const XML_Char *     attribute_name,
             const XML_Char *     attribute_type,
             const XML_Char *     default_value,
             int                  is_required);

This handler is called for each attribute; so a single <!ATTLIST declaration with multiple attributes declared will generate multiple calls to this handler.

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

element_name references a zero–terminated string representing the name of the element for which the attribute is being declared.

attribute_name references a zero–terminated string representing the attribute name.

attribute_type references a zero–terminated string representing the attribute type; it is the string representing the type in the declaration with whitespace removed.

default_value either is NULL or references a zero–terminated string representing the default value; is_required is true if the attribute is required. These two arguments are interpreted together:

— Function: void XML_SetAttlistDeclHandler (XML_Parser P, XML_AttlistDeclHandler H)

Set a handler for attribute list declarations in the DTD.


Next: , Previous: api handlers dtd attlist, Up: api handlers

3.5.7 DTD notation declaration

Notation declarations look like this:

     <!NOTATION bouncing SYSTEM 'http://localhost/bouncer'>
     <!NOTATION bouncing PUBLIC 'The Bouncer'>
     <!NOTATION bouncing PUBLIC 'The Bouncer'
        'http://localhost/bouncer'>
— Function Pointer Typedef: XML_NotationDeclHandler

Handler called when parsing a <!NOTATION declaration. Defined as:

          typedef void (* XML_NotationDeclHandler)
             (void           *    user_data,
              const XML_Char *    notation_name,
              const XML_Char *    base,
              const XML_Char *    system_id,
              const XML_Char *    public_id);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

notation_name references a zero–terminated string representing the notation name.

base is either NULL or references the zero–terminated string set with XML_SetBase().

system_id is either NULL or references a zero–terminated string representing the system identifier.

public_id is either NULL or references a zero–terminated string representing the public identifier.

— Function: void XML_SetNotationDeclHandler (XML_Parser p, XML_NotationDeclHandler h)

Set a handler that receives notation declarations.


Next: , Previous: api handlers dtd notation, Up: api handlers

3.5.8 Entity DTD declaration handlers

Entity declarations in a DTD look like the following:

     <!-- internal entity -->
     <!ENTITY stuff 'a'>
     
     <!-- external entities -->
     <!ENTITY stuff SYSTEM 'http://localhost/stuff'>
     
     <!ENTITY stuff PUBLIC 'The Stuff' 'http://localhost/stuff'>
     
     <!NOTATION stuffer SYSTEM 'http://localhost/stuffer'>
     <!ENTITY stuff SYSTEM 'http://localhost/stuff' NDATA stuffer>
     
     <!NOTATION stuffer SYSTEM 'http://localhost/stuffer'>
     <!ENTITY stuff PUBLIC 'The Stuff'
       'http://localhost/stuff' NDATA stuffer>
— Function Pointer Typedef: XML_EntityDeclHandler

Handler for entity declarations in the DTD; invoked whenever, while processing a DTD, the parser finds an <!ENTITY token. Defined as:

          typedef void (* XML_EntityDeclHandler)
            (void           * user_data,
             const XML_Char * entity_name,
             int              is_parameter_entity,
             const XML_Char * value,
             int              value_length,
             const XML_Char * base,
             const XML_Char * system_id,
             const XML_Char * public_id,
             const XML_Char * notation_name);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

entity_name references a zero–terminated string representing the entity name.

The is_parameter_entity argument will be non–zero in the case of parameter entities and zero otherwise.

The value string is not zero–terminated, the length is provided in the value_length parameter; do not use value_length to test for internal entities, since it is legal to have zero–length values, instead check for whether or not value is NULL.

base either is NULL or references a zero–terminated string representing the base set with XML_SetBase().

system_id either is NULL or references a zero–terminated string representing the system literal in a SYSTEM or PUBLIC external identifier.

public_id either is NULL or references a zero–terminated string representing the public literal identifier in a PUBLIC external identifier.

For internal entities: value will be non–NULL and system_id, public_id, and notation_name will all be NULL.

The notation_name argument will have a non–NULL value only for unparsed entity declarations.

— Function: void XML_SetEntityDeclHandler (XML_Parser P, XML_EntityDeclHandler H)

Set a handler that will be called for all entity declarations.

— Function Pointer Typedef: XML_UnparsedEntityDeclHandler

Handler for declarations of unparsed entities; these are entity declarations that have a notation (NDATA) field:

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

this handler is obsolete and is provided for backwards compatibility. Use instead XML_EntityDeclHandler(). Defined as:

          typedef void (* XML_UnparsedEntityDeclHandler)
             (void           *    user_data,
              const XML_Char *    entity_name,
              const XML_Char *    base,
              const XML_Char *    system_id,
              const XML_Char *    public_id,
              const XML_Char *    notation_name);
— Function: void XML_SetUnparsedEntityDeclHandler (XML_Parser P, XML_UnparsedEntityDeclHandler H)

Set a handler that receives declarations of unparsed entities.


Next: , Previous: api handlers dtd entity, Up: api handlers

3.5.9 Element handlers

— Function Pointer Typedef: XML_StartElementHandler

Handler for start and empty tags. Defined as:

          typedef void (* XML_StartElementHandler)
             (void           *    user_data,
              const XML_Char *    name,
              const XML_Char **   atts);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

name references a zero–terminated string representing the element type name.

Attributes are passed to the the start handler as a pointer atts 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.

Note that an empty tag generates a call to both start and end handlers (in that order).

— Function: void XML_SetStartElementHandler (XML_Parser P, XML_StartElementHandler H)

Set the handler for start and empty tags.

— Function Pointer Typedef: XML_EndElementHandler

Handler for end and empty tags. Defined as:

          typedef void (* XML_EndElementHandler)
             (void           *    user_data,
              const XML_Char *    name);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

name references a zero–terminated string representing the element type name.

An empty tag generates a call to both start and end handlers.

— Function: void XML_SetEndElementHandler (XML_Parser p, XML_EndElementHandler H)

Set the handler for end (and empty) tags.

— Function: void XML_SetElementHandler (XML_Parser P, XML_StartElementHandler S, XML_EndElementHandler E)

Set handlers for start and end tags with one call.


Next: , Previous: api handlers element, Up: api handlers

3.5.10 Character data handlers

Given the element:

     <greetings>Hello</greetings>

the character data is the Hello string.

— Function Pointer Typedef: XML_CharacterDataHandler

Handler for character data. Defined as:

          typedef void (* XML_CharacterDataHandler)
             (void           *    user_data,
              const XML_Char *    string,
              int                 string_len);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

The string the handler receives through string is not zero–terminated; we have to use the string_len 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 we are searching for a pattern in the text, it may be split across calls to this handler.

— Function: void XML_SetCharacterDataHandler (XML_Parser p, XML_CharacterDataHandler handler)

Set a text handler. Setting this handler to NULL may not immediately terminate callbacks if the parser is currently processing such a single block of contiguous markup–free text, as the parser will continue calling back until the end of the block is reached.


Next: , Previous: api handlers char data, Up: api handlers

3.5.11 Comment handlers

Comments in XML look like this:

     <!-- this text means nothing -->
— Function Pointer Typedef: XML_CommentHandler

Handler for comments. Defined as:

          typedef void (* XML_CommentHandler)
             (void           *    user_data,
              const XML_Char *    data);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

data is either NULL or references a zero–terminated string representing the text of the comment.

— Function: void XML_SetCommentHandler (XML_Parser p, XML_CommentHandler handler)

Set a handler for comments.


Next: , Previous: api handlers comment, Up: api handlers

3.5.12 Cdata handler

A CDATA element looks like this:

     <![CDATA[<stuff>interpreted literally</stuff>]]>

in which the text <stuff>interpreted literally</stuff> is handed to the XML_CharacterDataHandler handler.

— Function Pointer Typedef: XML_StartCdataSectionHandler

Handler called when the <![CDATA[ token is parsed. Defined as:

          typedef void (* XML_StartCdataSectionHandler) (void * user_data);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

— Function: void XML_SetStartCdataSectionHandler (XML_Parser p, XML_StartCdataSectionHandler start)

Set a handler that gets called at the beginning of a CDATA section.

— Function Pointer Typedef: XML_EndCdataSectionHandler

Handler called when the ]]> token ending a CDATA section is parsed. Defined as:

          typedef void (* XML_EndCdataSectionHandler) (void * user_data);

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

— Function: void XML_SetEndCdataSectionHandler (XML_Parser P, XML_EndCdataSectionHandler H)

Set a handler that gets called at the end of a CDATA section.

— Function: void XML_SetCdataSectionHandler (XML_Parser P, XML_StartCdataSectionHandler S, XML_EndCdataSectionHandler E)

Set both CDATA handlers: the one called at the start and the one called at the end.


Next: , Previous: api handlers cdata, Up: api handlers

3.5.13 Namespace handlers

— Function Pointer Typedef: XML_StartNamespaceDeclHandler

Handler called when a namespace is declared. Defined as:

          typedef void (* XML_StartNamespaceDeclHandler)
             (void           *    user_data,
              const XML_Char *    prefix,
              const XML_Char *    uri);

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.

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

prefix is either NULL or references a zero–terminated string representing the namespace prefix.

uri is either NULL or references a zero–terminated string representing the namespace URI.

— Function: void XML_SetStartNamespaceDeclHandler (XML_Parser P, XML_StartNamespaceDeclHandler H)

Set a handler to be called when a namespace is declared.

— Function Pointer Typedef: XML_EndNamespaceDeclHandler

Handler called when leaving the scope of a namespace declaration. Defined as:

          typedef void (* XML_EndNamespaceDeclHandler)
             (void           *    user_data,
              const XML_Char *    prefix);

This handler will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared.

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

prefix is either NULL or references a zero–terminated string representing the namespace prefix.

— Function: void XML_SetEndNamespaceDeclHandler (XML_Parser P, XML_EndNamespaceDeclHandler E)

Set a handler to be called when leaving the scope of a namespace declaration.

— Function: void XML_SetNamespaceDeclHandler (XML_Parser P, XML_StartNamespaceDeclHandler S, XML_EndNamespaceDeclHandler E)

Set both namespace declaration handlers with a single call.


Next: , Previous: api handlers namespace, Up: api handlers

3.5.14 Default handler

— Function Pointer Typedef: XML_DefaultHandler

Handler called for any characters in the document which would not 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. Defined as:

          typedef void (* XML_DefaultHandler)
             (void           *    user_data,
              const XML_Char *    string,
              int                 string_len);

The characters are passed exactly as they were present in the XML document except that they will be encoded in UTF-8 or UTF-16; note that a byte order mark character is not passed to the default handler. Line boundaries are not normalized.

There are no guarantees about how characters are divided between calls to the default handler: for example, a comment might be split between multiple calls.

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

string references a not zero–terminated string holding string_len characters representing the input data.

See also XML_DefaultCurrent().

— Function: void XML_SetDefaultHandler (XML_Parser P, XML_DefaultHandler H)

Set a handler for any characters in the document which wouldn't otherwise be handled. 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.

— Function: void XML_SetDefaultHandlerExpand (XML_Parser P, XML_DefaultHandler H)

Set a default handler, but does not inhibit the expansion of internal entity references. The entity reference will not be passed to the default handler.

See also XML_DefaultCurrent().

— Function: void XML_DefaultCurrent (XML_Parser p)

This function can be called within a handler for a start element, end element, processing instruction or character data. It causes the corresponding markup to be passed to the default handler set by XML_SetDefaultHandler() or XML_SetDefaultHandlerExpand(). It does nothing if there is not a default handler.


Next: , Previous: api handlers default, Up: api handlers

3.5.15 Special entity handlers

— Function Pointer Typedef: XML_SkippedEntityHandler

Handler for skipped entities. Defined as:

          typedef void (* XML_SkippedEntityHandler)
             (void           *    user_data,
              const XML_Char *    entity_name,
              int                 is_parameter_entity);

This is called in two situations:

  1. An entity reference is encountered for which no declaration has been read and this is not an error.
  2. An internal entity reference is read, but not expanded, because XML_SetDefaultHandler() has been called.

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

entity_name references a zero–terminated string representing the entity name.

is_parameter_entity is non–zero for a parameter entity and zero for a general entity.

NOTE Skipped parameter entities in declarations and skipped general entities in attribute values cannot be reported, because the event would be out of sync with the reporting of the declarations or attribute values.

— Function: void XML_SetSkippedEntityHandler (XML_Parser P, XML_SkippedEntityHandler H)

Set a skipped entity handler.


Next: , Previous: api handlers entity, Up: api handlers

3.5.16 Processing instruction handlers

Processing instructions look like this:

     <?scheme (display 123)?>

in which the target is scheme and the data is (display 123).

— Function Pointer Typedef: XML_ProcessingInstructionHandler

Handler for processing instructions. Defined as:

          typedef void (* XML_ProcessingInstructionHandler)
             (void           *    user_data,
              const XML_Char *    target,
              const XML_Char *    data);

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.

user_data references the custom value registered with XML_SetUserData() or XML_UseParserAsHandlerArg().

target references a zero–terminated string representing the processing instruction target.

data references a zero–terminated string representing the processing instruction data.

— Function: void XML_SetProcessingInstructionHandler (XML_Parser P, XML_ProcessingInstructionHandler H)

Set a handler for processing instructions.


Previous: api handlers procinst, Up: api handlers

3.5.17 Character encoding handlers

— Function Pointer Typedef: XML_UnknownEncodingHandler

Handler to deal with encodings other than the built in set. Defined as:

          typedef int (* XML_UnknownEncodingHandler)
             (void           *    handler_data,
              const XML_Char *    name,
              XML_Encoding   *    info);

If the handler knows how to deal with an encoding with the given name, it should fill in the info data structure and return XML_STATUS_OK; otherwise it should return XML_STATUS_ERROR.

The handler will be called at most once per parsed (external) entity.

handler_data is the custom pointer registered with XML_SetUnknownEncodingHandler().

name references a zero–terminated string representing the encoding name.

info references a data structure to be filled with stuff needed to handle the encoding.

— Struct Typedef: XML_Encoding

Structure representing an encoding.

int map[256]
The map array contains information for every possible leading byte in a byte sequence.
  • If the corresponding value is N >= 0, then it's a single byte sequence and the byte encodes the Unicode code point N.
  • If the value is -1, then that byte is invalid as the initial byte in a sequence.
  • If the value is -N, 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 the field convert.

void * data
Custom pointer used as first argument to the functions referenced by the fields convert and release.
int (* convert) (void * data, const char * str)
Pointer to the function used to convert a sequence of input characters; the convert pointer may be NULL if there are only single byte codes. The string str is not zero–terminated and points at the sequence of bytes to be converted. This function may return -1 if the sequence itself is invalid.
void (* release) (void * data)
The function pointed at by release is called by the parser when it is finished with the encoding; it may be NULL.

— Function: void XML_SetUnknownEncodingHandler (XML_Parser P, XML_UnknownEncodingHandler H, void * encoding_data)

Set a handler to deal with encodings other than the built in set. This function should be called before XML_Parse() or XML_ParseBuffer() have been called on the given parser.

The optional application data pointer encoding_data will be passed back to the handler.


Next: , Previous: api handlers, Up: api

3.6 Parse position and error reporting functions

These are the functions we'll want to call when the parse functions return XML_STATUS_ERROR (a parse error has occurred), although the position reporting functions are useful outside of errors.

The position reported is the byte position (in the original document or entity encoding) of the first of the sequence of characters that generated the current event (or the error that caused the parse functions to return XML_STATUS_ERROR). This is not true for callbacks triggered by declarations in the document prologue, in which case the exact position reported is somewhere in the relevant markup, but not necessarily as meaningful as for other events.

The position reporting functions are accurate only outside of the DTD; in other words, they usually return bogus information when called from within a DTD declaration handler.

— Function: enum XML_Error XML_GetErrorCode (XML_Parser p)

Return what type of error has occurred.

— Function: const XML_LChar * XML_ErrorString (enum XML_Error 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().

— Function: XML_Index XML_GetCurrentByteIndex (XML_Parser p)

Return the byte offset of the position. This always corresponds to the values returned by XML_GetCurrentLineNumber() and XML_GetCurrentColumnNumber().

— Function: XML_Size XML_GetCurrentLineNumber (XML_Parser p)

Return the line number of the position. The first line is reported as 1.

— Function: XML_Size XML_GetCurrentColumnNumber (XML_Parser p)

Return the offset, from the beginning of the current line, of the position.

— Function: int XML_GetCurrentByteCount (XML_Parser p)

Return the number of bytes in the current event, 0 if the event is inside a reference to an internal entity and for the end–tag event for empty element tags (the later can be used to distinguish empty–element tags from empty elements using separate start and end tags).

— Function: const char * XML_GetInputContext (XML_Parser p, int * offset, int * size)

Return the parser's input buffer, sets the integer pointed at by offset to the offset within this buffer of the current parse position, and set the integer pointed at by size to the size of the returned buffer.

This should only be called from within a handler during an active parse and the returned buffer should only be referred to from within the handler that made the call. This input buffer contains the untranslated bytes of the input.

Only a limited amount of context is kept, so if the event triggering a call spans over a very large amount of input, the actual parse position may be before the beginning of the buffer.

If XML_CONTEXT_BYTES is not defined, this will always return NULL.


Next: , Previous: api report, Up: api

3.7 Expat version

— Function: XML_LChar * XML_ExpatVersion (void)

Return the library version as a string (e.g. expat_1.95.1).

— Struct Typedef: XML_Expat_Version

Type of structure representing the Expat version. Description of public fields follows.

int major
The major version number.
int minor
The minor version number.
int micro
The micro version number.

— Function: struct XML_Expat_Version XML_ExpatVersionInfo (void)

Return the library version information as a structure (yes, the whole structure is the returned value).

— Macro: XML_MAJOR_VERSION
— Macro: XML_MINOR_VERSION
— Macro: XML_MICRO_VERSION

These macros are defined to support compile–time tests of the library version. Testing these constants is currently the best way to determine if particular parts of the Expat API are available.


Next: , Previous: api version, Up: api

3.8 Expat features

— Enumeration: XML_FeatureEnum

Type of values representing Expat features.

— Macro: XML_FEATURE_END
— Macro: XML_FEATURE_UNICODE
— Macro: XML_FEATURE_UNICODE_WCHAR_T
— Macro: XML_FEATURE_DTD
— Macro: XML_FEATURE_CONTEXT_BYTES
— Macro: XML_FEATURE_MIN_SIZE
— Macro: XML_FEATURE_SIZEOF_XML_CHAR
— Macro: XML_FEATURE_SIZEOF_XML_LCHAR
— Macro: XML_FEATURE_NS
— Macro: XML_FEATURE_LARGE_SIZ

Values of the XML_FeatureEnum enumeration representing Expat features.

— Struct Typedef: XML_Feature

Type of the records representing Expat features. Public fields description follows.

enum XML_FeatureEnum feature
A constant representing the feature.
XML_LChar * name
Pointer to a statically allocated string representing the name of the feature.
long int value
A value associated to the feature.

— Function: const XML_Feature * XML_GetFeatureList (void)

Return a list of “feature” records, providing details on how Expat was configured at compile time. Most applications should not need to worry about this, but this information is otherwise not available from Expat. This function allows code that needs to check these features to do so at runtime.

The return value is a pointer to a statically allocated array of XML_Feature, terminated by a record with the feature field set to XML_FEATURE_END and name field set to NULL.

Since an application that requires this kind of information needs to determine the type of character the name points to, records for the XML_FEATURE_SIZEOF_XML_CHAR and XML_FEATURE_SIZEOF_XML_LCHAR will be located at the beginning of the list, followed by XML_FEATURE_UNICODE and XML_FEATURE_UNICODE_WCHAR_T, if they are present at all.

Some features have an associated value. If there isn't an associated value, the value field is set to 0. At this time, the following features have been defined to have values:

XML_FEATURE_SIZEOF_XML_CHAR
The number of bytes occupied by one XML_Char character.
XML_FEATURE_SIZEOF_XML_LCHAR
The number of bytes occupied by one XML_LChar character.
XML_FEATURE_CONTEXT_BYTES
The maximum number of characters of context which can be reported by XML_GetInputContext().


Next: , Previous: api features, Up: api

3.9 Parser associated memory

The following functions allow external code to share the memory allocator an XML_Parser() has been configured to use. This is especially useful for third–party libraries that interact with a parser object created by application code, or heavily layered applications. This can be essential when using dynamically loaded libraries which use different C standard libraries (this can happen on Windows, at least).

— Function: void * XML_MemMalloc (XML_Parser p, size_t size)

Allocate size bytes of memory using the allocator the parser object has been configured to use. Return a pointer to the memory or NULL on failure. Memory allocated in this way must be freed using XML_MemFree().

— Function: void * XML_MemRealloc (XML_Parser p, void * ptr, size_t size)

Allocate or reallocate size bytes of memory using the allocator the parser object has been configured to use.

ptr must point to a block of memory allocated by XML_MemMalloc() or XML_MemRealloc(), or be NULL.

When reallocating, this function tries to expand the block pointed to by ptr if possible.

Return a pointer to the memory or NULL on failure. On success, the original block has either been expanded or freed. On failure, the original block has not been freed; the caller is responsible for freeing the original block.

Memory allocated in this way must be freed using XML_MemFree().

— Function: void XML_MemFree (XML_Parser p, void * ptr)

Free a block of memory pointed to by ptr. The block must have been allocated by XML_MemMalloc() or XML_MemRealloc(), or be NULL.


Previous: api memory, Up: api

3.10 Miscellaneous functions

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

— Function: void XML_SetUserData (XML_Parser p, void * user_data)
— Function: void * XML_GetUserData (XML_Parser p)

Set or get the user data pointer that gets passed to handlers, overwriting any previous value. The application is responsible for managing the memory associated with user_data.

— Function: void XML_UseParserAsHandlerArg (XML_Parser p)

Set the parser pointer itself as user_data argument for the handlers. The user data can still be obtained using the XML_GetUserData() function.

— Function: enum XML_Status XML_SetBase (XML_Parser p, const XML_Char * base)

Set the base to be used for resolving relative URIs in system identifiers. The string referenced by base is duplicated. If base is NULL the base is reset.

Return XML_STATUS_OK if successful. Return XML_STATUS_ERROR if there's no memory to duplicate the base.

— Function: const XML_Char * XML_GetBase (XML_Parser p)

Return the current base for resolving relative URIs. The returned value can be NULL if no base was set.

— Function: 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 times 2, thus giving the offset in the atts array passed to the start tag handler of the first attribute set due to defaults. It supplies information for the last call to a start handler. If called inside a start handler, then that means the current call.

— Function: int XML_GetIdAttributeIndex (XML_Parser p)

Return the index of the ID attribute passed in the atts array in the last call to XML_StartElementHandler(), or -1 if there is no ID attribute. If called inside a start handler, then that means the current call.

— Function: enum XML_Status XML_SetEncoding (XML_Parser p, const XML_Char * encoding)

Set the encoding to be used by the parser, return XML_STATUS_OK if successful.

The string referenced by encoding is duplicated, the return value is XML_STATUS_ERROR if there is not enough memory to duplicate it.

This function must not be called after XML_Parse() or XML_ParseBuffer() have been called on the given parser, the return value is XML_STATUS_ERROR if the parser is in the XML_PARSING or XML_SUSPENDED status.

Calling this function is equivalent to passing a non–NULL encoding argument to the parser creation functions.

— Function: int XML_SetParamEntityParsing (XML_Parser p, enum XML_ParamEntityParsing code)

Enable parsing of parameter entities according to code, including the external parameter entity that is the external DTD subset. The choices for code are:

          XML_PARAM_ENTITY_PARSING_NEVER
          XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE
          XML_PARAM_ENTITY_PARSING_ALWAYS
— Function: enum XML_Error XML_UseForeignDTD (XML_Parser p, XML_Bool use_dtd)

Allow an application to provide an external subset for the document type declaration for documents which do not specify an external subset of their own.

For documents which specify an external subset in their DOCTYPE declaration, the application–provided subset will be ignored.

If the document does not contain a DOCTYPE declaration at all and use_dtd is true, the application–provided subset will be parsed, but the XML_StartDoctypeDeclHandler and XML_EndDoctypeDeclHandler functions, if set, will not be called.

The setting of parameter entity parsing will be honored (refer to XML_SetParamEntityParsing()).

The application–provided external subset is read by calling the external entity reference handler set via XML_SetExternalEntityRefHandler() with both publicId and systemId set to NULL.

Return values are:

XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
If this function is called after parsing has begun; use_dtd is ignored.
XML_ERROR_FEATURE_REQUIRES_XML_DTD
If called when Expat has been compiled without DTD support, it returns
XML_ERROR_NONE
Otherwise.
NOTE For the purpose of checking WFC: Entity Declared, passing use_dtd == XML_TRUE will make the parser behave as if the document had a DTD with an external subset. This holds true even if the external entity reference handler returns without action.

— Function: void XML_SetReturnNSTriplet (XML_Parser p, int do_nst)

This function only has an effect when using a parser created with XML_ParserCreateNS(), i.e. when namespace processing is in effect. The do_nst argument sets whether or not prefixes are returned with names qualified with a namespace prefix. If this function is called with non–zero do_nst, then namespace qualified names (that is qualified with a prefix as opposed to belonging to a default namespace) are returned as a triplet with the three parts separated by the namespace separator specified when the parser was created. The order of returned parts is URI, local name, and prefix.

If do_nst is zero, then namespaces are reported in the default manner, URI then local name separated by the namespace separator.


Next: , Previous: api, Up: Top

Appendix A Document license

Copyright © 1998, 1999, 2000 Thai Open Source Software Center Ltd and Clark Cooper.

Copyright © 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Next: , Previous: document license, Up: Top

Appendix B Bibliography and references

“Extensible Markup Language (XML) 1.0 (Fifth Edition)”. W3C Recommendation 26 November 2008.

http://www.w3.org/TR/REC-xml/


Next: , Previous: references, Up: Top

Appendix C An entry for each concept


Next: , Previous: concept index, Up: Top

Appendix D An entry for each function.


Next: , Previous: function index, Up: Top

Appendix E An entry for each variable.


Previous: variable index, Up: Top

Appendix F An entry for each type.

Table of Contents