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
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.
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()
XML_SetElementHandler()
XML_SetCharacterDataHandler()
XML_Parse()
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.
start()
handler does all the work: It prints two indenting
spaces for every level of ancestor elements, then it prints the element
and attribute information; finally it increments the global ‘Depth’
variable.
end()
handler simply does the bookkeeping work of decrementing
‘Depth’.
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
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.
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.
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.
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
XML_NS
XML_UNICODE
XML_Char
. This is
implied if XML_UNICODE_WCHAR_T
is defined.
XML_UNICODE_WCHAR_T
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
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
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
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.
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.
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.
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; } } ... }
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.
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.
$@\^'{}~
).
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.
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.
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
XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE
XML_PARAM_ENTITY_PARSING_ALWAYS
In order to read an external DTD, we also have to set an external entity reference handler as described in using entity.
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:
XInclude
specification.
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.
Constants of type
enum XML_Status
.
Constant of type
enum XML_Status
. Document not well–formed (invalid token).
Constant of type
enum XML_Status
. Duplicate attribute.
Constant of type
enum XML_Status
. Junk after document element.
Constant of type
enum XML_Status
. Illegal parameter entity reference.
Constant of type
enum XML_Status
. Undefined entity.
Constant of type
enum XML_Status
. Recursive entity reference.
Constant of type
enum XML_Status
. Asynchronous entity.
Constant of type
enum XML_Status
. Reference to invalid character number.
Constant of type
enum XML_Status
. Reference to binary entity.
Constant of type
enum XML_Status
. Reference to external entity in attribute.
Constant of type
enum XML_Status
. XML or text declaration not at start of entity.
Constant of type
enum XML_Status
. Unknown encoding.
Constant of type
enum XML_Status
. Encoding specified in XML declaration is incorrect.
Constant of type
enum XML_Status
. UnclosedCDATA
section.
Constant of type
enum XML_Status
. Error in processing external entity reference.
Constant of type
enum XML_Status
. Document is not standalone.
Constant of type
enum XML_Status
. Unexpected parser state (send a bug report).
Constant of type
enum XML_Status
. Entity declared in parameter entity.
Constant of type
enum XML_Status
. Requested feature requiresXML_DTD
support in Expat.
Constant of type
enum XML_Status
. Cannot change setting once parsing has begun.
Constant of type
enum XML_Status
. Must not undeclare prefix.
Constant of type
enum XML_Status
. Incomplete markup in parameter entity.
Constant of type
enum XML_Status
. XML declaration not well–formed.
Constant of type
enum XML_Status
. Text declaration not well–formed.
Constant of type
enum XML_Status
. Illegal character(s) in public identifier.
Constant of type
enum XML_Status
. Parser not suspended.
Constant of type
enum XML_Status
. Cannot suspend in external parameter entity.
Constant of type
enum XML_Status
. Reserved prefixxml
must not be undeclared or bound to another namespace name.
Constant of type
enum XML_Status
. Reserved prefixxmlns
must not be declared or undeclared
Constant of type
enum XML_Status
. Prefix must not be bound to one of the reserved namespace names.
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-1Any other value will invoke
XML_UnknownEncodingHandler
.
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.
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;
Free memory used by the parser. Our application is responsible for freeing any memory associated with user data.
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 returnXML_FALSE
in that case. ReturnsXML_TRUE
on success. Our application is responsible for dealing with any memory associated with user data.
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.
Type of the return values.
XML_STATUS_ERROR
- Error.
XML_STATUS_OK
- Success.
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
, otherwiseXML_STATUS_ERROR
.
This is just like
XML_Parse()
, except in this case Expat provides the buffer. By obtaining the buffer from Expat with theXML_GetBuffer()
function, the application can avoid double copying of the input.
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; }
Stop parsing causing
XML_Parse()
orXML_ParseBuffer()
to return. Must be called from within a callback handler, except when aborting (when resumable isXML_FALSE
) an already suspended parser. Some call–backs may still follow because they would otherwise get lost, including:
- The end element handler for empty elements when stopped in the start element handler.
- The end namespace declaration handler when stopped in the end element handler.
- The character data handler when stopped in the character data handler while making multiple call-backs on a contiguous chunk of characters.
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
, otherwiseXML_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()
andXML_ParseBuffer()
returnXML_STATUS_SUSPENDED
. Otherwise, parsing is aborted, that is,XML_Parse()
andXML_ParseBuffer()
returnXML_STATUS_ERROR
with error codeXML_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 callXML_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.
Resume parsing after it has been suspended with
XML_StopParser()
. Must not be called from within a handler callback. Return the same status codes ofXML_Parse()
orXML_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 callXML_ResumeParser()
on it at the appropriate moment.NOTE New in Expat 1.95.8.
Parser status values. Defined symbols are:
XML_INITIALIZED XML_PARSING XML_FINISHED XML_SUSPENDED
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.
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.
Construct a new
XML_Parser
object for parsing an external general entity. context is the context argument passed in a call to aXML_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).
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 beNULL
.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.
- This handler returns a status indicator (an integer).
XML_STATUS_OK
should be returned for successful handling of the external entity reference. ReturningXML_STATUS_ERROR
indicates failure, and causes the calling parser to return anXML_ERROR_EXTERNAL_ENTITY_HANDLING
error.- 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.
Set an external entity reference handler.
Set the argument passed to the
XML_ExternalEntityRefHandler
. If arg is notNULL
, it is the new value passed to the handler set usingXML_SetExternalEntityRefHandler()
; if arg isNULL
, 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 theXML_ExternalEntityRefHandler
do not match. This function takes avoid *
to be passed to the handler, while the handler accepts anXML_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.
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.
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'>
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()
orXML_UseParserAsHandlerArg()
.version is either
NULL
or references a zero–terminated string representing the XML specification version; such string is always1.0
. The way to distinguish the kind of input is that version will beNULL
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 asno
.+1
- Indicating that
standalone
was given asyes
.
Set a handler that is called for XML declarations and also for text declarations discovered in external entities.
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()
orXML_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 toyes
in an XML declaration.If this handler returns
XML_STATUS_ERROR
: the parser will throw anXML_ERROR_NOT_STANDALONE
error.
Set a handler that is called if the document is not “standalone”.
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.
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()
orXML_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.
Set a handler called at the start of a
<!DOCTYPE
declaration, before any external or internal subset is parsed.
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()
orXML_UseParserAsHandlerArg()
.
Set a handler that is called at the end of a
<!DOCTYPE
declaration, after parsing any external subset.
Set both
<!DOCTYPE
handlers with one call.
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”.
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()
orXML_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 usingXML_FreeContentModel()
.
Set or unset a handler for element DTD declarations.
Deallocate the model argument passed to the
XML_ElementDeclHandler
handler. This function should not be used for any other purpose.
Values of the
XML_Content_Type
enumeration. See the description of the fieldtype
in the structureXML_Content
for details.
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 imagineREP
to stand for “replicated”.XML_CQUANT_PLUS
- When the quantifier
+
is used.
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 thechildren
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_SEQwhen this instance represents a child element, the value of this field is always
XML_CTYPE_NAME
.If the type is
EMPTY
orANY
:quant
isXML_CQUANT_NONE
and the other fields are zero orNULL
.If the type is
MIXED
:quant
isXML_CQUANT_NONE
orXML_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_PLUSif 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
isNULL
or a pointer to an array of structures describing the children elements; the number of elements in the array isnumchildren
.One of the following cases is possible:
- When
type
isXML_CTYPE_EMPTY
orXML_CTYPE_ANY
: the array is empty.- When
type
isXML_CTYPE_CHOICE
orXML_CTYPE_SEQ
: the array has a number of entries equal to the number of children elements.- When
type
isXML_CTYPE_MIXED
and the element's content specification is(#PCDATA)
: the array is empty.- When
type
isXML_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.
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()
orXML_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:
- For
#IMPLIED
attributes:default_value
isNULL
and is_required is true.- For
#REQUIRED
attributes:default_value
isNULL
and is_required is false.- For
#FIXED
attributes: default_value references a string and is_required is true.
Set a handler for attribute list declarations in the DTD.
Notation declarations look like this:
<!NOTATION bouncing SYSTEM 'http://localhost/bouncer'> <!NOTATION bouncing PUBLIC 'The Bouncer'> <!NOTATION bouncing PUBLIC 'The Bouncer' 'http://localhost/bouncer'>
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()
orXML_UseParserAsHandlerArg()
.notation_name references a zero–terminated string representing the notation name.
base is either
NULL
or references the zero–terminated string set withXML_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.
Set a handler that receives notation declarations.
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>
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()
orXML_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 withXML_SetBase()
.system_id either is
NULL
or references a zero–terminated string representing the system literal in aSYSTEM
orPUBLIC
external identifier.public_id either is
NULL
or references a zero–terminated string representing the public literal identifier in aPUBLIC
external identifier.For internal entities: value will be non–
NULL
and system_id, public_id, and notation_name will all beNULL
.The notation_name argument will have a non–
NULL
value only for unparsed entity declarations.
Set a handler that will be called for all entity declarations.
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);
Set a handler that receives declarations of unparsed entities.
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()
orXML_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).
Set the handler for start and empty tags.
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()
orXML_UseParserAsHandlerArg()
.name references a zero–terminated string representing the element type name.
An empty tag generates a call to both start and end handlers.
Set the handler for end (and empty) tags.
Set handlers for start and end tags with one call.
Given the element:
<greetings>Hello</greetings>
the character data is the Hello
string.
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()
orXML_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.
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.
Comments in XML look like this:
<!-- this text means nothing -->
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()
orXML_UseParserAsHandlerArg()
.data is either
NULL
or references a zero–terminated string representing the text of the comment.
Set a handler for comments.
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.
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()
orXML_UseParserAsHandlerArg()
.
Set a handler that gets called at the beginning of a
CDATA
section.
Handler called when the
]]>
token ending aCDATA
section is parsed. Defined as:typedef void (* XML_EndCdataSectionHandler) (void * user_data);user_data references the custom value registered with
XML_SetUserData()
orXML_UseParserAsHandlerArg()
.
Set a handler that gets called at the end of a
CDATA
section.
Set both
CDATA
handlers: the one called at the start and the one called at the end.
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()
orXML_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.
Set a handler to be called when a namespace is declared.
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()
orXML_UseParserAsHandlerArg()
.prefix is either
NULL
or references a zero–terminated string representing the namespace prefix.
Set a handler to be called when leaving the scope of a namespace declaration.
Set both namespace declaration handlers with a single call.
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()
orXML_UseParserAsHandlerArg()
.string references a not zero–terminated string holding string_len characters representing the input data.
See also
XML_DefaultCurrent()
.
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.
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()
.
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()
orXML_SetDefaultHandlerExpand()
. It does nothing if there is not a default handler.
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:
- An entity reference is encountered for which no declaration has been read and this is not an error.
- 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()
orXML_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.
Set a skipped entity handler.
Processing instructions look like this:
<?scheme (display 123)?>
in which the target is scheme
and the data is (display
123)
.
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()
orXML_UseParserAsHandlerArg()
.target references a zero–terminated string representing the processing instruction target.
data references a zero–terminated string representing the processing instruction data.
Set a handler for processing instructions.
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 returnXML_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.
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
andrelease
.int (* convert) (void * data, const char * str)
- Pointer to the function used to convert a sequence of input characters; the
convert
pointer may beNULL
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 beNULL
.
Set a handler to deal with encodings other than the built in set. This function should be called before
XML_Parse()
orXML_ParseBuffer()
have been called on the given parser.The optional application data pointer encoding_data will be passed back to the handler.
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.
Return a string describing the error corresponding to code. The code should be one of the enums that can be returned from
XML_GetErrorCode()
.
Return the byte offset of the position. This always corresponds to the values returned by
XML_GetCurrentLineNumber()
andXML_GetCurrentColumnNumber()
.
Return the line number of the position. The first line is reported as 1.
Return the offset, from the beginning of the current line, of the position.
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).
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 returnNULL
.
Return the library version as a string (e.g.
expat_1.95.1
).
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.
Return the library version information as a structure (yes, the whole structure is the returned value).
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.
Values of the
XML_FeatureEnum
enumeration representing Expat features.
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.
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 thefeature
field set toXML_FEATURE_END
andname
field set toNULL
.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
andXML_FEATURE_SIZEOF_XML_LCHAR
will be located at the beginning of the list, followed byXML_FEATURE_UNICODE
andXML_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()
.
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).
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 usingXML_MemFree()
.
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()
orXML_MemRealloc()
, or beNULL
.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()
.
Free a block of memory pointed to by ptr. The block must have been allocated by
XML_MemMalloc()
orXML_MemRealloc()
, or beNULL
.
The functions in this section either obtain state information from the parser or can be used to dynamicly set parser options.
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.
Set the parser pointer itself as user_data argument for the handlers. The user data can still be obtained using the
XML_GetUserData()
function.
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. ReturnXML_STATUS_ERROR
if there's no memory to duplicate the base.
Return the current base for resolving relative URIs. The returned value can be
NULL
if no base was set.
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.
Return the index of the
ID
attribute passed in the atts array in the last call toXML_StartElementHandler()
, or-1
if there is noID
attribute. If called inside a start handler, then that means the current call.
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()
orXML_ParseBuffer()
have been called on the given parser, the return value isXML_STATUS_ERROR
if the parser is in theXML_PARSING
orXML_SUSPENDED
status.Calling this function is equivalent to passing a non–
NULL
encoding argument to the parser creation functions.
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
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 theXML_StartDoctypeDeclHandler
andXML_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 toNULL
.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.
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.
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.
“Extensible Markup Language (XML) 1.0 (Fifth Edition)”. W3C Recommendation 26 November 2008.
XML_DefaultCurrent
: api handlers defaultXML_ErrorString
: api reportXML_ExpatVersion
: api versionXML_ExpatVersionInfo
: api versionXML_ExternalEntityParserCreate
: api externalXML_FEATURE_CONTEXT_BYTES
: api featuresXML_FEATURE_DTD
: api featuresXML_FEATURE_END
: api featuresXML_FEATURE_LARGE_SIZ
: api featuresXML_FEATURE_MIN_SIZE
: api featuresXML_FEATURE_NS
: api featuresXML_FEATURE_SIZEOF_XML_CHAR
: api featuresXML_FEATURE_SIZEOF_XML_LCHAR
: api featuresXML_FEATURE_UNICODE
: api featuresXML_FEATURE_UNICODE_WCHAR_T
: api featuresXML_FreeContentModel
: api handlers dtd elementXML_GetBase
: api miscXML_GetBuffer
: api parseXML_GetCurrentByteCount
: api reportXML_GetCurrentByteIndex
: api reportXML_GetCurrentColumnNumber
: api reportXML_GetCurrentLineNumber
: api reportXML_GetErrorCode
: api reportXML_GetFeatureList
: api featuresXML_GetIdAttributeIndex
: api miscXML_GetInputContext
: api reportXML_GetParsingStatus
: api parseXML_GetSpecifiedAttributeCount
: api miscXML_GetUserData
: api miscXML_MAJOR_VERSION
: api versionXML_MemFree
: api memoryXML_MemMalloc
: api memoryXML_MemRealloc
: api memoryXML_MICRO_VERSION
: api versionXML_MINOR_VERSION
: api versionXML_Parse
: api parseXML_ParseBuffer
: api parseXML_ParserCreate
: api createXML_ParserCreate_MM
: api createXML_ParserCreateNS
: api createXML_ParserFree
: api createXML_ParserReset
: api createXML_ResumeParser
: api parseXML_SetAttlistDeclHandler
: api handlers dtd attlistXML_SetBase
: api miscXML_SetCdataSectionHandler
: api handlers cdataXML_SetCharacterDataHandler
: api handlers char dataXML_SetCommentHandler
: api handlers commentXML_SetDefaultHandler
: api handlers defaultXML_SetDefaultHandlerExpand
: api handlers defaultXML_SetDoctypeDeclHandler
: api handlers dtd doctypeXML_SetElementDeclHandler
: api handlers dtd elementXML_SetElementHandler
: api handlers elementXML_SetEncoding
: api miscXML_SetEndCdataSectionHandler
: api handlers cdataXML_SetEndDoctypeDeclHandler
: api handlers dtd doctypeXML_SetEndElementHandler
: api handlers elementXML_SetEndNamespaceDeclHandler
: api handlers namespaceXML_SetEntityDeclHandler
: api handlers dtd entityXML_SetExternalEntityRefHandler
: api externalXML_SetExternalEntityRefHandlerArg
: api externalXML_SetNamespaceDeclHandler
: api handlers namespaceXML_SetNotationDeclHandler
: api handlers dtd notationXML_SetNotStandaloneHandler
: api handlers standaloneXML_SetParamEntityParsing
: api miscXML_SetProcessingInstructionHandler
: api handlers procinstXML_SetReturnNSTriplet
: api miscXML_SetSkippedEntityHandler
: api handlers entityXML_SetStartCdataSectionHandler
: api handlers cdataXML_SetStartDoctypeDeclHandler
: api handlers dtd doctypeXML_SetStartElementHandler
: api handlers elementXML_SetStartNamespaceDeclHandler
: api handlers namespaceXML_SetUnknownEncodingHandler
: api handlers encodingXML_SetUnparsedEntityDeclHandler
: api handlers dtd entityXML_SetUserData
: api miscXML_SetXmlDeclHandler
: api handlers xml declXML_StopParser
: api parseXML_UseForeignDTD
: api miscXML_UseParserAsHandlerArg
: api miscXML_CQUANT_NONE
: api handlers dtd elementXML_CQUANT_OPT
: api handlers dtd elementXML_CQUANT_PLUS
: api handlers dtd elementXML_CQUANT_REP
: api handlers dtd elementXML_CTYPE_ANY
: api handlers dtd elementXML_CTYPE_CHOICE
: api handlers dtd elementXML_CTYPE_EMPTY
: api handlers dtd elementXML_CTYPE_MIXED
: api handlers dtd elementXML_CTYPE_NAME
: api handlers dtd elementXML_CTYPE_SEQ
: api handlers dtd elementXML_ERROR_ABORTED
: api errorsXML_ERROR_ASYNC_ENTITY
: api errorsXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
: api errorsXML_ERROR_BAD_CHAR_REF
: api errorsXML_ERROR_BINARY_ENTITY_REF
: api errorsXML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
: api errorsXML_ERROR_DUPLICATE_ATTRIBUTE
: api errorsXML_ERROR_ENTITY_DECLARED_IN_PE
: api errorsXML_ERROR_EXTERNAL_ENTITY_HANDLING
: api errorsXML_ERROR_FEATURE_REQUIRES_XML_DTD
: api errorsXML_ERROR_FINISHED
: api errorsXML_ERROR_INCOMPLETE_PE
: api errorsXML_ERROR_INCORRECT_ENCODING
: api errorsXML_ERROR_INVALID_TOKEN
: api errorsXML_ERROR_JUNK_AFTER_DOC_ELEMENT
: api errorsXML_ERROR_MISPLACED_XML_PI
: api errorsXML_ERROR_NO_ELEMENTS
: api errorsXML_ERROR_NO_MEMORY
: api errorsXML_ERROR_NONE
: api errorsXML_ERROR_NOT_STANDALONE
: api errorsXML_ERROR_NOT_SUSPENDED
: api errorsXML_ERROR_PARAM_ENTITY_REF
: api errorsXML_ERROR_PARTIAL_CHAR
: api errorsXML_ERROR_PUBLICID
: api errorsXML_ERROR_RECURSIVE_ENTITY_REF
: api errorsXML_ERROR_RESERVED_NAMESPACE_UR
: api errorsXML_ERROR_RESERVED_PREFIX_XML
: api errorsXML_ERROR_RESERVED_PREFIX_XMLNS
: api errorsXML_ERROR_SUSPEND_PE
: api errorsXML_ERROR_SUSPENDED
: api errorsXML_ERROR_SYNTAX
: api errorsXML_ERROR_TAG_MISMATCH
: api errorsXML_ERROR_TEXT_DECL
: api errorsXML_ERROR_UNBOUND_PREFIX
: api errorsXML_ERROR_UNCLOSED_CDATA_SECTION
: api errorsXML_ERROR_UNCLOSED_TOKEN
: api errorsXML_ERROR_UNDECLARING_PREFIX
: api errorsXML_ERROR_UNDEFINED_ENTITY
: api errorsXML_ERROR_UNEXPECTED_STATE
: api errorsXML_ERROR_UNKNOWN_ENCODING
: api errorsXML_ERROR_XML_DECL
: api errorsXML_STATUS_ERROR
: api errorsXML_STATUS_OK
: api errorsXML_STATUS_SUSPENDED
: api errorsenum XML_Parsing
: api parseenum XML_Status
: api parseXML_AttlistDeclHandler
: api handlers dtd attlistXML_CharacterDataHandler
: api handlers char dataXML_CommentHandler
: api handlers commentXML_Content
: api handlers dtd elementXML_Content_Quant
: api handlers dtd elementXML_Content_Type
: api handlers dtd elementXML_DefaultHandler
: api handlers defaultXML_ElementDeclHandler
: api handlers dtd elementXML_Encoding
: api handlers encodingXML_EndCdataSectionHandler
: api handlers cdataXML_EndDoctypeDeclHandler
: api handlers dtd doctypeXML_EndElementHandler
: api handlers elementXML_EndNamespaceDeclHandler
: api handlers namespaceXML_EntityDeclHandler
: api handlers dtd entityXML_Error
: api errorsXML_Expat_Version
: api versionXML_ExternalEntityRefHandler
: api externalXML_Feature
: api featuresXML_FeatureEnum
: api featuresXML_NotationDeclHandler
: api handlers dtd notationXML_NotStandaloneHandler
: api handlers standaloneXML_ParsingStatus
: api parseXML_ProcessingInstructionHandler
: api handlers procinstXML_SkippedEntityHandler
: api handlers entityXML_StartCdataSectionHandler
: api handlers cdataXML_StartDoctypeDeclHandler
: api handlers dtd doctypeXML_StartElementHandler
: api handlers elementXML_StartNamespaceDeclHandler
: api handlers namespaceXML_Status
: api errorsXML_UnknownEncodingHandler
: api handlers encodingXML_UnparsedEntityDeclHandler
: api handlers dtd entityXML_XmlDeclHandler
: api handlers xml decl