xref: /freebsd/contrib/expat/doc/reference.html (revision fe9278888fd4414abe2d922e469cf608005f4c65)
1<?xml version="1.0" encoding="iso-8859-1"?>
2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4<html>
5<head>
6<!--
7                            __  __            _
8                         ___\ \/ /_ __   __ _| |_
9                        / _ \\  /| '_ \ / _` | __|
10                       |  __//  \| |_) | (_| | |_
11                        \___/_/\_\ .__/ \__,_|\__|
12                                 |_| XML parser
13
14   Copyright (c) 2000      Clark Cooper <coopercc@users.sourceforge.net>
15   Copyright (c) 2000-2004 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
16   Copyright (c) 2002-2012 Karl Waclawek <karl@waclawek.net>
17   Copyright (c) 2017-2025 Sebastian Pipping <sebastian@pipping.org>
18   Copyright (c) 2017      Jakub Wilk <jwilk@jwilk.net>
19   Copyright (c) 2021      Tomas Korbar <tkorbar@redhat.com>
20   Copyright (c) 2021      Nicolas Cavallari <nicolas.cavallari@green-communications.fr>
21   Copyright (c) 2022      Thijs Schreijer <thijs@thijsschreijer.nl>
22   Copyright (c) 2023      Hanno Böck <hanno@gentoo.org>
23   Copyright (c) 2023      Sony Corporation / Snild Dolkow <snild@sony.com>
24   Licensed under the MIT license:
25
26   Permission is  hereby granted,  free of charge,  to any  person obtaining
27   a  copy  of  this  software   and  associated  documentation  files  (the
28   "Software"),  to  deal in  the  Software  without restriction,  including
29   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
30   distribute, sublicense, and/or sell copies of the Software, and to permit
31   persons  to whom  the Software  is  furnished to  do so,  subject to  the
32   following conditions:
33
34   The above copyright  notice and this permission notice  shall be included
35   in all copies or substantial portions of the Software.
36
37   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
38   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
39   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
40   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
41   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
42   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
43   USE OR OTHER DEALINGS IN THE SOFTWARE.
44-->
45  <title>Expat XML Parser</title>
46  <meta name="author" content="Clark Cooper, coopercc@netheaven.com" />
47  <meta http-equiv="Content-Style-Type" content="text/css" />
48  <link href="ok.min.css" rel="stylesheet" type="text/css" />
49  <link href="style.css" rel="stylesheet" type="text/css" />
50</head>
51<body>
52  <div>
53    <h1>
54      The Expat XML Parser
55      <small>Release 2.7.1</small>
56    </h1>
57  </div>
58<div class="content">
59
60<p>Expat is a library, written in C, for parsing XML documents. It's
61the underlying XML parser for the open source Mozilla project, Perl's
62<code>XML::Parser</code>, Python's <code>xml.parsers.expat</code>, and
63other open-source XML parsers.</p>
64
65<p>This library is the creation of James Clark, who's also given us
66groff (an nroff look-alike), Jade (an implementation of ISO's DSSSL
67stylesheet language for SGML), XP (a Java XML parser package), XT (a
68Java XSL engine).  James was also the technical lead on the XML
69Working Group at W3C that produced the XML specification.</p>
70
71<p>This is free software, licensed under the <a
72href="../COPYING">MIT/X Consortium license</a>. You may download it
73from <a href="https://libexpat.github.io/">the Expat home page</a>.
74</p>
75
76<p>The bulk of this document was originally commissioned as an article
77by <a href="https://www.xml.com/">XML.com</a>. They graciously allowed
78Clark Cooper to retain copyright and to distribute it with Expat.
79This version has been substantially extended to include documentation
80on features which have been added since the original article was
81published, and additional information on using the original
82interface.</p>
83
84<hr />
85<h2>Table of Contents</h2>
86<ul>
87  <li><a href="#overview">Overview</a></li>
88  <li><a href="#building">Building and Installing</a></li>
89  <li><a href="#using">Using Expat</a></li>
90  <li><a href="#reference">Reference</a>
91  <ul>
92    <li><a href="#creation">Parser Creation Functions</a>
93    <ul>
94      <li><a href="#XML_ParserCreate">XML_ParserCreate</a></li>
95      <li><a href="#XML_ParserCreateNS">XML_ParserCreateNS</a></li>
96      <li><a href="#XML_ParserCreate_MM">XML_ParserCreate_MM</a></li>
97      <li><a href="#XML_ExternalEntityParserCreate">XML_ExternalEntityParserCreate</a></li>
98      <li><a href="#XML_ParserFree">XML_ParserFree</a></li>
99      <li><a href="#XML_ParserReset">XML_ParserReset</a></li>
100    </ul>
101    </li>
102    <li><a href="#parsing">Parsing Functions</a>
103    <ul>
104      <li><a href="#XML_Parse">XML_Parse</a></li>
105      <li><a href="#XML_ParseBuffer">XML_ParseBuffer</a></li>
106      <li><a href="#XML_GetBuffer">XML_GetBuffer</a></li>
107      <li><a href="#XML_StopParser">XML_StopParser</a></li>
108      <li><a href="#XML_ResumeParser">XML_ResumeParser</a></li>
109      <li><a href="#XML_GetParsingStatus">XML_GetParsingStatus</a></li>
110    </ul>
111    </li>
112    <li><a href="#setting">Handler Setting Functions</a>
113    <ul>
114      <li><a href="#XML_SetStartElementHandler">XML_SetStartElementHandler</a></li>
115      <li><a href="#XML_SetEndElementHandler">XML_SetEndElementHandler</a></li>
116      <li><a href="#XML_SetElementHandler">XML_SetElementHandler</a></li>
117      <li><a href="#XML_SetCharacterDataHandler">XML_SetCharacterDataHandler</a></li>
118      <li><a href="#XML_SetProcessingInstructionHandler">XML_SetProcessingInstructionHandler</a></li>
119      <li><a href="#XML_SetCommentHandler">XML_SetCommentHandler</a></li>
120      <li><a href="#XML_SetStartCdataSectionHandler">XML_SetStartCdataSectionHandler</a></li>
121      <li><a href="#XML_SetEndCdataSectionHandler">XML_SetEndCdataSectionHandler</a></li>
122      <li><a href="#XML_SetCdataSectionHandler">XML_SetCdataSectionHandler</a></li>
123      <li><a href="#XML_SetDefaultHandler">XML_SetDefaultHandler</a></li>
124      <li><a href="#XML_SetDefaultHandlerExpand">XML_SetDefaultHandlerExpand</a></li>
125      <li><a href="#XML_SetExternalEntityRefHandler">XML_SetExternalEntityRefHandler</a></li>
126      <li><a href="#XML_SetExternalEntityRefHandlerArg">XML_SetExternalEntityRefHandlerArg</a></li>
127      <li><a href="#XML_SetSkippedEntityHandler">XML_SetSkippedEntityHandler</a></li>
128      <li><a href="#XML_SetUnknownEncodingHandler">XML_SetUnknownEncodingHandler</a></li>
129      <li><a href="#XML_SetStartNamespaceDeclHandler">XML_SetStartNamespaceDeclHandler</a></li>
130      <li><a href="#XML_SetEndNamespaceDeclHandler">XML_SetEndNamespaceDeclHandler</a></li>
131      <li><a href="#XML_SetNamespaceDeclHandler">XML_SetNamespaceDeclHandler</a></li>
132      <li><a href="#XML_SetXmlDeclHandler">XML_SetXmlDeclHandler</a></li>
133      <li><a href="#XML_SetStartDoctypeDeclHandler">XML_SetStartDoctypeDeclHandler</a></li>
134      <li><a href="#XML_SetEndDoctypeDeclHandler">XML_SetEndDoctypeDeclHandler</a></li>
135      <li><a href="#XML_SetDoctypeDeclHandler">XML_SetDoctypeDeclHandler</a></li>
136      <li><a href="#XML_SetElementDeclHandler">XML_SetElementDeclHandler</a></li>
137      <li><a href="#XML_SetAttlistDeclHandler">XML_SetAttlistDeclHandler</a></li>
138      <li><a href="#XML_SetEntityDeclHandler">XML_SetEntityDeclHandler</a></li>
139      <li><a href="#XML_SetUnparsedEntityDeclHandler">XML_SetUnparsedEntityDeclHandler</a></li>
140      <li><a href="#XML_SetNotationDeclHandler">XML_SetNotationDeclHandler</a></li>
141      <li><a href="#XML_SetNotStandaloneHandler">XML_SetNotStandaloneHandler</a></li>
142    </ul>
143    </li>
144    <li><a href="#position">Parse Position and Error Reporting Functions</a>
145    <ul>
146      <li><a href="#XML_GetErrorCode">XML_GetErrorCode</a></li>
147      <li><a href="#XML_ErrorString">XML_ErrorString</a></li>
148      <li><a href="#XML_GetCurrentByteIndex">XML_GetCurrentByteIndex</a></li>
149      <li><a href="#XML_GetCurrentLineNumber">XML_GetCurrentLineNumber</a></li>
150      <li><a href="#XML_GetCurrentColumnNumber">XML_GetCurrentColumnNumber</a></li>
151      <li><a href="#XML_GetCurrentByteCount">XML_GetCurrentByteCount</a></li>
152      <li><a href="#XML_GetInputContext">XML_GetInputContext</a></li>
153    </ul>
154    </li>
155    <li>
156      <a href="#attack-protection">Attack Protection</a>
157      <ul>
158        <li><a href="#XML_SetBillionLaughsAttackProtectionMaximumAmplification">XML_SetBillionLaughsAttackProtectionMaximumAmplification</a></li>
159        <li><a href="#XML_SetBillionLaughsAttackProtectionActivationThreshold">XML_SetBillionLaughsAttackProtectionActivationThreshold</a></li>
160        <li><a href="#XML_SetReparseDeferralEnabled">XML_SetReparseDeferralEnabled</a></li>
161      </ul>
162    </li>
163    <li><a href="#miscellaneous">Miscellaneous Functions</a>
164    <ul>
165      <li><a href="#XML_SetUserData">XML_SetUserData</a></li>
166      <li><a href="#XML_GetUserData">XML_GetUserData</a></li>
167      <li><a href="#XML_UseParserAsHandlerArg">XML_UseParserAsHandlerArg</a></li>
168      <li><a href="#XML_SetBase">XML_SetBase</a></li>
169      <li><a href="#XML_GetBase">XML_GetBase</a></li>
170      <li><a href="#XML_GetSpecifiedAttributeCount">XML_GetSpecifiedAttributeCount</a></li>
171      <li><a href="#XML_GetIdAttributeIndex">XML_GetIdAttributeIndex</a></li>
172      <li><a href="#XML_GetAttributeInfo">XML_GetAttributeInfo</a></li>
173      <li><a href="#XML_SetEncoding">XML_SetEncoding</a></li>
174      <li><a href="#XML_SetParamEntityParsing">XML_SetParamEntityParsing</a></li>
175      <li><a href="#XML_SetHashSalt">XML_SetHashSalt</a></li>
176      <li><a href="#XML_UseForeignDTD">XML_UseForeignDTD</a></li>
177      <li><a href="#XML_SetReturnNSTriplet">XML_SetReturnNSTriplet</a></li>
178      <li><a href="#XML_DefaultCurrent">XML_DefaultCurrent</a></li>
179      <li><a href="#XML_ExpatVersion">XML_ExpatVersion</a></li>
180      <li><a href="#XML_ExpatVersionInfo">XML_ExpatVersionInfo</a></li>
181      <li><a href="#XML_GetFeatureList">XML_GetFeatureList</a></li>
182      <li><a href="#XML_FreeContentModel">XML_FreeContentModel</a></li>
183      <li><a href="#XML_MemMalloc">XML_MemMalloc</a></li>
184      <li><a href="#XML_MemRealloc">XML_MemRealloc</a></li>
185      <li><a href="#XML_MemFree">XML_MemFree</a></li>
186    </ul>
187    </li>
188  </ul>
189  </li>
190</ul>
191
192<hr />
193<h2><a name="overview">Overview</a></h2>
194
195<p>Expat is a stream-oriented parser. You register callback (or
196handler) functions with the parser and then start feeding it the
197document.  As the parser recognizes parts of the document, it will
198call the appropriate handler for that part (if you've registered one.)
199The document is fed to the parser in pieces, so you can start parsing
200before you have all the document. This also allows you to parse really
201huge documents that won't fit into memory.</p>
202
203<p>Expat can be intimidating due to the many kinds of handlers and
204options you can set. But you only need to learn four functions in
205order to do 90% of what you'll want to do with it:</p>
206
207<dl>
208
209<dt><code><a href= "#XML_ParserCreate"
210             >XML_ParserCreate</a></code></dt>
211  <dd>Create a new parser object.</dd>
212
213<dt><code><a href= "#XML_SetElementHandler"
214             >XML_SetElementHandler</a></code></dt>
215  <dd>Set handlers for start and end tags.</dd>
216
217<dt><code><a href= "#XML_SetCharacterDataHandler"
218             >XML_SetCharacterDataHandler</a></code></dt>
219  <dd>Set handler for text.</dd>
220
221<dt><code><a href= "#XML_Parse"
222             >XML_Parse</a></code></dt>
223  <dd>Pass a buffer full of document to the parser</dd>
224</dl>
225
226<p>These functions and others are described in the <a
227href="#reference">reference</a> part of this document. The reference
228section also describes in detail the parameters passed to the
229different types of handlers.</p>
230
231<p>Let's look at a very simple example program that only uses 3 of the
232above functions (it doesn't need to set a character handler.) The
233program <a href="../examples/outline.c">outline.c</a> prints an
234element outline, indenting child elements to distinguish them from the
235parent element that contains them. The start handler does all the
236work.  It prints two indenting spaces for every level of ancestor
237elements, then it prints the element and attribute
238information. Finally it increments the global <code>Depth</code>
239variable.</p>
240
241<pre class="eg">
242int Depth;
243
244void XMLCALL
245start(void *data, const char *el, const char **attr) {
246  int i;
247
248  for (i = 0; i &lt; Depth; i++)
249    printf("  ");
250
251  printf("%s", el);
252
253  for (i = 0; attr[i]; i += 2) {
254    printf(" %s='%s'", attr[i], attr[i + 1]);
255  }
256
257  printf("\n");
258  Depth++;
259}  /* End of start handler */
260</pre>
261
262<p>The end tag simply does the bookkeeping work of decrementing
263<code>Depth</code>.</p>
264<pre class="eg">
265void XMLCALL
266end(void *data, const char *el) {
267  Depth--;
268}  /* End of end handler */
269</pre>
270
271<p>Note the <code>XMLCALL</code> annotation used for the callbacks.
272This is used to ensure that the Expat and the callbacks are using the
273same calling convention in case the compiler options used for Expat
274itself and the client code are different.  Expat tries not to care
275what the default calling convention is, though it may require that it
276be compiled with a default convention of "cdecl" on some platforms.
277For code which uses Expat, however, the calling convention is
278specified by the <code>XMLCALL</code> annotation on most platforms;
279callbacks should be defined using this annotation.</p>
280
281<p>The <code>XMLCALL</code> annotation was added in Expat 1.95.7, but
282existing working Expat applications don't need to add it (since they
283are already using the "cdecl" calling convention, or they wouldn't be
284working).  The annotation is only needed if the default calling
285convention may be something other than "cdecl".  To use the annotation
286safely with older versions of Expat, you can conditionally define it
287<em>after</em> including Expat's header file:</p>
288
289<pre class="eg">
290#include &lt;expat.h&gt;
291
292#ifndef XMLCALL
293#if defined(_MSC_EXTENSIONS) &amp;&amp; !defined(__BEOS__) &amp;&amp; !defined(__CYGWIN__)
294#define XMLCALL __cdecl
295#elif defined(__GNUC__)
296#define XMLCALL __attribute__((cdecl))
297#else
298#define XMLCALL
299#endif
300#endif
301</pre>
302
303<p>After creating the parser, the main program just has the job of
304shoveling the document to the parser so that it can do its work.</p>
305
306<hr />
307<h2><a name="building">Building and Installing Expat</a></h2>
308
309<p>The Expat distribution comes as a compressed (with GNU gzip) tar
310file.  You may download the latest version from <a href=
311"https://sourceforge.net/projects/expat/" >Source Forge</a>.  After
312unpacking this, cd into the directory. Then follow either the Win32
313directions or Unix directions below.</p>
314
315<h3>Building under Win32</h3>
316
317<p>If you're using the GNU compiler under cygwin, follow the Unix
318directions in the next section. Otherwise if you have Microsoft's
319Developer Studio installed,
320you can use CMake to generate a <code>.sln</code> file, e.g.
321<code>
322cmake -G"Visual Studio 16 2019" -DCMAKE_BUILD_TYPE=RelWithDebInfo .
323</code>, and build Expat using <code>msbuild /m expat.sln</code> after.</p>
324
325<p>Alternatively, you may download the Win32 binary package that
326contains the "expat.h" include file and a pre-built DLL.</p>
327
328<h3>Building under Unix (or GNU)</h3>
329
330<p>First you'll need to run the configure shell script in order to
331configure the Makefiles and headers for your system.</p>
332
333<p>If you're happy with all the defaults that configure picks for you,
334and you have permission on your system to install into /usr/local, you
335can install Expat with this sequence of commands:</p>
336
337<pre class="eg">
338./configure
339make
340make install
341</pre>
342
343<p>There are some options that you can provide to this script, but the
344only one we'll mention here is the <code>--prefix</code> option. You
345can find out all the options available by running configure with just
346the <code>--help</code> option.</p>
347
348<p>By default, the configure script sets things up so that the library
349gets installed in <code>/usr/local/lib</code> and the associated
350header file in <code>/usr/local/include</code>.  But if you were to
351give the option, <code>--prefix=/home/me/mystuff</code>, then the
352library and header would get installed in
353<code>/home/me/mystuff/lib</code> and
354<code>/home/me/mystuff/include</code> respectively.</p>
355
356<h3>Configuring Expat Using the Pre-Processor</h3>
357
358<p>Expat's feature set can be configured using a small number of
359pre-processor definitions.  The symbols are:</p>
360
361<dl class="cpp-symbols">
362<dt><a name="XML_GE">XML_GE</a></dt>
363<dd>
364Added in Expat 2.6.0.
365Include support for
366<a href="https://www.w3.org/TR/2006/REC-xml-20060816/#sec-physical-struct">general entities</a>
367(syntax <code>&amp;e1;</code> to reference and
368syntax <code>&lt;!ENTITY e1 'value1'&gt;</code> (an internal general entity) or
369<code>&lt;!ENTITY e2 SYSTEM 'file2'&gt;</code> (an external general entity) to declare).
370With <code>XML_GE</code> enabled, general entities will be replaced by their declared replacement text;
371for this to work for <em>external</em> general entities, in addition an
372<code><a href="#XML_SetExternalEntityRefHandler">XML_ExternalEntityRefHandler</a></code> must be set using
373<code><a href="#XML_SetExternalEntityRefHandler">XML_SetExternalEntityRefHandler</a></code>.
374Also, enabling <code>XML_GE</code> makes
375the functions <code><a href="#XML_SetBillionLaughsAttackProtectionMaximumAmplification">
376XML_SetBillionLaughsAttackProtectionMaximumAmplification</a></code> and <code>
377<a href="#XML_SetBillionLaughsAttackProtectionActivationThreshold">
378XML_SetBillionLaughsAttackProtectionActivationThreshold</a></code> available.
379<br/>
380With <code>XML_GE</code> disabled, Expat has a smaller memory footprint and can be faster, but will
381not load external general entities and will replace all general entities
382(except the <a href="https://www.w3.org/TR/2006/REC-xml-20060816/#sec-predefined-ent">predefined five</a>:
383<code>amp</code>, <code>apos</code>, <code>gt</code>, <code>lt</code>, <code>quot</code>)
384with a self-reference:
385for example, referencing an entity <code>e1</code> via <code>&amp;e1;</code> will be replaced
386by text <code>&amp;e1;</code>.
387</dd>
388
389<dt><a name="XML_DTD">XML_DTD</a></dt>
390<dd>Include support for using and reporting DTD-based content.  If
391this is defined, default attribute values from an external DTD subset
392are reported and attribute value normalization occurs based on the
393type of attributes defined in the external subset.  Without
394this, Expat has a smaller memory footprint and can be faster, but will
395not load external parameter entities or process conditional sections. If defined, makes
396the functions <code><a
397href="#XML_SetBillionLaughsAttackProtectionMaximumAmplification">
398XML_SetBillionLaughsAttackProtectionMaximumAmplification</a></code> and <code>
399<a href="#XML_SetBillionLaughsAttackProtectionActivationThreshold">
400XML_SetBillionLaughsAttackProtectionActivationThreshold</a></code> available.</dd>
401
402<dt><a name="XML_NS">XML_NS</a></dt>
403<dd>When defined, support for the <cite><a href=
404"https://www.w3.org/TR/REC-xml-names/" >Namespaces in XML</a></cite>
405specification is included.</dd>
406
407<dt><a name="XML_UNICODE">XML_UNICODE</a></dt>
408<dd>When defined, character data reported to the application is
409encoded in UTF-16 using wide characters of the type
410<code>XML_Char</code>.  This is implied if
411<code>XML_UNICODE_WCHAR_T</code> is defined.</dd>
412
413<dt><a name="XML_UNICODE_WCHAR_T">XML_UNICODE_WCHAR_T</a></dt>
414<dd>If defined, causes the <code>XML_Char</code> character type to be
415defined using the <code>wchar_t</code> type; otherwise, <code>unsigned
416short</code> is used.  Defining this implies
417<code>XML_UNICODE</code>.</dd>
418
419<dt><a name="XML_LARGE_SIZE">XML_LARGE_SIZE</a></dt>
420<dd>If defined, causes the <code>XML_Size</code> and <code>XML_Index</code>
421integer types to be at least 64 bits in size. This is intended to support
422processing of very large input streams, where the return values of
423<code><a href="#XML_GetCurrentByteIndex" >XML_GetCurrentByteIndex</a></code>,
424<code><a href="#XML_GetCurrentLineNumber" >XML_GetCurrentLineNumber</a></code> and
425<code><a href="#XML_GetCurrentColumnNumber" >XML_GetCurrentColumnNumber</a></code>
426could overflow. It may not be supported by all compilers, and is turned
427off by default.</dd>
428
429<dt><a name="XML_CONTEXT_BYTES">XML_CONTEXT_BYTES</a></dt>
430<dd>The number of input bytes of markup context which the parser will
431ensure are available for reporting via <code><a href=
432"#XML_GetInputContext" >XML_GetInputContext</a></code>.  This is
433normally set to 1024, and must be set to a positive integer to enable.
434If this is set to zero, the input context will not be available and <code><a
435href= "#XML_GetInputContext" >XML_GetInputContext</a></code> will
436always report <code>NULL</code>.  Without this, Expat has a smaller memory
437footprint and can be faster.</dd>
438
439<dt><a name="XML_STATIC">XML_STATIC</a></dt>
440<dd>On Windows, this should be set if Expat is going to be linked
441statically with the code that calls it; this is required to get all
442the right MSVC magic annotations correct.  This is ignored on other
443platforms.</dd>
444
445<dt><a name="XML_ATTR_INFO">XML_ATTR_INFO</a></dt>
446<dd>If defined, makes the additional function <code><a href=
447"#XML_GetAttributeInfo" >XML_GetAttributeInfo</a></code> available
448for reporting attribute byte offsets.</dd>
449</dl>
450
451<hr />
452<h2><a name="using">Using Expat</a></h2>
453
454<h3>Compiling and Linking Against Expat</h3>
455
456<p>Unless you installed Expat in a location not expected by your
457compiler and linker, all you have to do to use Expat in your programs
458is to include the Expat header (<code>#include &lt;expat.h&gt;</code>)
459in your files that make calls to it and to tell the linker that it
460needs to link against the Expat library.  On Unix systems, this would
461usually be done with the <code>-lexpat</code> argument.  Otherwise,
462you'll need to tell the compiler where to look for the Expat header
463and the linker where to find the Expat library.  You may also need to
464take steps to tell the operating system where to find this library at
465run time.</p>
466
467<p>On a Unix-based system, here's what a Makefile might look like when
468Expat is installed in a standard location:</p>
469
470<pre class="eg">
471CC=cc
472LDFLAGS=
473LIBS= -lexpat
474xmlapp: xmlapp.o
475        $(CC) $(LDFLAGS) -o xmlapp xmlapp.o $(LIBS)
476</pre>
477
478<p>If you installed Expat in, say, <code>/home/me/mystuff</code>, then
479the Makefile would look like this:</p>
480
481<pre class="eg">
482CC=cc
483CFLAGS= -I/home/me/mystuff/include
484LDFLAGS=
485LIBS= -L/home/me/mystuff/lib -lexpat
486xmlapp: xmlapp.o
487        $(CC) $(LDFLAGS) -o xmlapp xmlapp.o $(LIBS)
488</pre>
489
490<p>You'd also have to set the environment variable
491<code>LD_LIBRARY_PATH</code> to <code>/home/me/mystuff/lib</code> (or
492to <code>${LD_LIBRARY_PATH}:/home/me/mystuff/lib</code> if
493LD_LIBRARY_PATH already has some directories in it) in order to run
494your application.</p>
495
496<h3>Expat Basics</h3>
497
498<p>As we saw in the example in the overview, the first step in parsing
499an XML document with Expat is to create a parser object. There are <a
500href="#creation">three functions</a> in the Expat API for creating a
501parser object.  However, only two of these (<code><a href=
502"#XML_ParserCreate" >XML_ParserCreate</a></code> and <code><a href=
503"#XML_ParserCreateNS" >XML_ParserCreateNS</a></code>) can be used for
504constructing a parser for a top-level document.  The object returned
505by these functions is an opaque pointer (i.e. "expat.h" declares it as
506void *) to data with further internal structure. In order to free the
507memory associated with this object you must call <code><a href=
508"#XML_ParserFree" >XML_ParserFree</a></code>. Note that if you have
509provided any <a href="#userdata">user data</a> that gets stored in the
510parser, then your application is responsible for freeing it prior to
511calling <code>XML_ParserFree</code>.</p>
512
513<p>The objects returned by the parser creation functions are good for
514parsing only one XML document or external parsed entity. If your
515application needs to parse many XML documents, then it needs to create
516a parser object for each one. The best way to deal with this is to
517create a higher level object that contains all the default
518initialization you want for your parser objects.</p>
519
520<p>Walking through a document hierarchy with a stream oriented parser
521will require a good stack mechanism in order to keep track of current
522context.  For instance, to answer the simple question, "What element
523does this text belong to?" requires a stack, since the parser may have
524descended into other elements that are children of the current one and
525has encountered this text on the way out.</p>
526
527<p>The things you're likely to want to keep on a stack are the
528currently opened element and it's attributes. You push this
529information onto the stack in the start handler and you pop it off in
530the end handler.</p>
531
532<p>For some tasks, it is sufficient to just keep information on what
533the depth of the stack is (or would be if you had one.) The outline
534program shown above presents one example. Another such task would be
535skipping over a complete element. When you see the start tag for the
536element you want to skip, you set a skip flag and record the depth at
537which the element started.  When the end tag handler encounters the
538same depth, the skipped element has ended and the flag may be
539cleared. If you follow the convention that the root element starts at
5401, then you can use the same variable for skip flag and skip
541depth.</p>
542
543<pre class="eg">
544void
545init_info(Parseinfo *info) {
546  info->skip = 0;
547  info->depth = 1;
548  /* Other initializations here */
549}  /* End of init_info */
550
551void XMLCALL
552rawstart(void *data, const char *el, const char **attr) {
553  Parseinfo *inf = (Parseinfo *) data;
554
555  if (! inf->skip) {
556    if (should_skip(inf, el, attr)) {
557      inf->skip = inf->depth;
558    }
559    else
560      start(inf, el, attr);     /* This does rest of start handling */
561  }
562
563  inf->depth++;
564}  /* End of rawstart */
565
566void XMLCALL
567rawend(void *data, const char *el) {
568  Parseinfo *inf = (Parseinfo *) data;
569
570  inf->depth--;
571
572  if (! inf->skip)
573    end(inf, el);              /* This does rest of end handling */
574
575  if (inf->skip == inf->depth)
576    inf->skip = 0;
577}  /* End rawend */
578</pre>
579
580<p>Notice in the above example the difference in how depth is
581manipulated in the start and end handlers. The end tag handler should
582be the mirror image of the start tag handler. This is necessary to
583properly model containment. Since, in the start tag handler, we
584incremented depth <em>after</em> the main body of start tag code, then
585in the end handler, we need to manipulate it <em>before</em> the main
586body.  If we'd decided to increment it first thing in the start
587handler, then we'd have had to decrement it last thing in the end
588handler.</p>
589
590<h3 id="userdata">Communicating between handlers</h3>
591
592<p>In order to be able to pass information between different handlers
593without using globals, you'll need to define a data structure to hold
594the shared variables. You can then tell Expat (with the <code><a href=
595"#XML_SetUserData" >XML_SetUserData</a></code> function) to pass a
596pointer to this structure to the handlers.  This is the first
597argument received by most handlers.  In the <a href="#reference"
598>reference section</a>, an argument to a callback function is named
599<code>userData</code> and have type <code>void *</code> if the user
600data is passed; it will have the type <code>XML_Parser</code> if the
601parser itself is passed.  When the parser is passed, the user data may
602be retrieved using <code><a href="#XML_GetUserData"
603>XML_GetUserData</a></code>.</p>
604
605<p>One common case where multiple calls to a single handler may need
606to communicate using an application data structure is the case when
607content passed to the character data handler (set by <code><a href=
608"#XML_SetCharacterDataHandler"
609>XML_SetCharacterDataHandler</a></code>) needs to be accumulated.  A
610common first-time mistake with any of the event-oriented interfaces to
611an XML parser is to expect all the text contained in an element to be
612reported by a single call to the character data handler.  Expat, like
613many other XML parsers, reports such data as a sequence of calls;
614there's no way to know when the end of the sequence is reached until a
615different callback is made.  A buffer referenced by the user data
616structure proves both an effective and convenient place to accumulate
617character data.</p>
618
619<!-- XXX example needed here -->
620
621
622<h3>XML Version</h3>
623
624<p>Expat is an XML 1.0 parser, and as such never complains based on
625the value of the <code>version</code> pseudo-attribute in the XML
626declaration, if present.</p>
627
628<p>If an application needs to check the version number (to support
629alternate processing), it should use the <code><a href=
630"#XML_SetXmlDeclHandler" >XML_SetXmlDeclHandler</a></code> function to
631set a handler that uses the information in the XML declaration to
632determine what to do.  This example shows how to check that only a
633version number of <code>"1.0"</code> is accepted:</p>
634
635<pre class="eg">
636static int wrong_version;
637static XML_Parser parser;
638
639static void XMLCALL
640xmldecl_handler(void            *userData,
641                const XML_Char  *version,
642                const XML_Char  *encoding,
643                int              standalone)
644{
645  static const XML_Char Version_1_0[] = {'1', '.', '0', 0};
646
647  int i;
648
649  for (i = 0; i &lt; (sizeof(Version_1_0) / sizeof(Version_1_0[0])); ++i) {
650    if (version[i] != Version_1_0[i]) {
651      wrong_version = 1;
652      /* also clear all other handlers: */
653      XML_SetCharacterDataHandler(parser, NULL);
654      ...
655      return;
656    }
657  }
658  ...
659}
660</pre>
661
662<h3>Namespace Processing</h3>
663
664<p>When the parser is created using the <code><a href=
665"#XML_ParserCreateNS" >XML_ParserCreateNS</a></code>, function, Expat
666performs namespace processing. Under namespace processing, Expat
667consumes <code>xmlns</code> and <code>xmlns:...</code> attributes,
668which declare namespaces for the scope of the element in which they
669occur. This means that your start handler will not see these
670attributes.  Your application can still be informed of these
671declarations by setting namespace declaration handlers with <a href=
672"#XML_SetNamespaceDeclHandler"
673><code>XML_SetNamespaceDeclHandler</code></a>.</p>
674
675<p>Element type and attribute names that belong to a given namespace
676are passed to the appropriate handler in expanded form. By default
677this expanded form is a concatenation of the namespace URI, the
678separator character (which is the 2nd argument to <code><a href=
679"#XML_ParserCreateNS" >XML_ParserCreateNS</a></code>), and the local
680name (i.e. the part after the colon). Names with undeclared prefixes
681are not well-formed when namespace processing is enabled, and will
682trigger an error. Unprefixed attribute names are never expanded,
683and unprefixed element names are only expanded when they are in the
684scope of a default namespace.</p>
685
686<p>However if <code><a href= "#XML_SetReturnNSTriplet"
687>XML_SetReturnNSTriplet</a></code> has been called with a non-zero
688<code>do_nst</code> parameter, then the expanded form for names with
689an explicit prefix is a concatenation of: URI, separator, local name,
690separator, prefix.</p>
691
692<p>You can set handlers for the start of a namespace declaration and
693for the end of a scope of a declaration with the <code><a href=
694"#XML_SetNamespaceDeclHandler" >XML_SetNamespaceDeclHandler</a></code>
695function.  The StartNamespaceDeclHandler is called prior to the start
696tag handler and the EndNamespaceDeclHandler is called after the
697corresponding end tag that ends the namespace's scope.  The namespace
698start handler gets passed the prefix and URI for the namespace.  For a
699default namespace declaration (xmlns='...'), the prefix will be
700<code>NULL</code>.
701The URI will be <code>NULL</code> for the case where the default namespace is being
702unset.  The namespace end handler just gets the prefix for the closing
703scope.</p>
704
705<p>These handlers are called for each declaration. So if, for
706instance, a start tag had three namespace declarations, then the
707StartNamespaceDeclHandler would be called three times before the start
708tag handler is called, once for each declaration.</p>
709
710<h3>Character Encodings</h3>
711
712<p>While XML is based on Unicode, and every XML processor is required
713to recognized UTF-8 and UTF-16 (1 and 2 byte encodings of Unicode),
714other encodings may be declared in XML documents or entities. For the
715main document, an XML declaration may contain an encoding
716declaration:</p>
717<pre>
718&lt;?xml version="1.0" encoding="ISO-8859-2"?&gt;
719</pre>
720
721<p>External parsed entities may begin with a text declaration, which
722looks like an XML declaration with just an encoding declaration:</p>
723<pre>
724&lt;?xml encoding="Big5"?&gt;
725</pre>
726
727<p>With Expat, you may also specify an encoding at the time of
728creating a parser. This is useful when the encoding information may
729come from a source outside the document itself (like a higher level
730protocol.)</p>
731
732<p><a name="builtin_encodings"></a>There are four built-in encodings
733in Expat:</p>
734<ul>
735<li>UTF-8</li>
736<li>UTF-16</li>
737<li>ISO-8859-1</li>
738<li>US-ASCII</li>
739</ul>
740
741<p>Anything else discovered in an encoding declaration or in the
742protocol encoding specified in the parser constructor, triggers a call
743to the <code>UnknownEncodingHandler</code>. This handler gets passed
744the encoding name and a pointer to an <code>XML_Encoding</code> data
745structure. Your handler must fill in this structure and return
746<code>XML_STATUS_OK</code> if it knows how to deal with the
747encoding. Otherwise the handler should return
748<code>XML_STATUS_ERROR</code>.  The handler also gets passed a pointer
749to an optional application data structure that you may indicate when
750you set the handler.</p>
751
752<p>Expat places restrictions on character encodings that it can
753support by filling in the <code>XML_Encoding</code> structure.
754include file:</p>
755<ol>
756<li>Every ASCII character that can appear in a well-formed XML document
757must be represented by a single byte, and that byte must correspond to
758it's ASCII encoding (except for the characters $@\^'{}~)</li>
759<li>Characters must be encoded in 4 bytes or less.</li>
760<li>All characters encoded must have Unicode scalar values less than or
761equal to 65535 (0xFFFF)<em>This does not apply to the built-in support
762for UTF-16 and UTF-8</em></li>
763<li>No character may be encoded by more that one distinct sequence of
764bytes</li>
765</ol>
766
767<p><code>XML_Encoding</code> contains an array of integers that
768correspond to the 1st byte of an encoding sequence. If the value in
769the array for a byte is zero or positive, then the byte is a single
770byte encoding that encodes the Unicode scalar value contained in the
771array. A -1 in this array indicates a malformed byte. If the value is
772-2, -3, or -4, then the byte is the beginning of a 2, 3, or 4 byte
773sequence respectively. Multi-byte sequences are sent to the convert
774function pointed at in the <code>XML_Encoding</code> structure. This
775function should return the Unicode scalar value for the sequence or -1
776if the sequence is malformed.</p>
777
778<p>One pitfall that novice Expat users are likely to fall into is that
779although Expat may accept input in various encodings, the strings that
780it passes to the handlers are always encoded in UTF-8 or UTF-16
781(depending on how Expat was compiled). Your application is responsible
782for any translation of these strings into other encodings.</p>
783
784<h3>Handling External Entity References</h3>
785
786<p>Expat does not read or parse external entities directly. Note that
787any external DTD is a special case of an external entity.  If you've
788set no <code>ExternalEntityRefHandler</code>, then external entity
789references are silently ignored. Otherwise, it calls your handler with
790the information needed to read and parse the external entity.</p>
791
792<p>Your handler isn't actually responsible for parsing the entity, but
793it is responsible for creating a subsidiary parser with <code><a href=
794"#XML_ExternalEntityParserCreate"
795>XML_ExternalEntityParserCreate</a></code> that will do the job. This
796returns an instance of <code>XML_Parser</code> that has handlers and
797other data structures initialized from the parent parser. You may then
798use <code><a href= "#XML_Parse" >XML_Parse</a></code> or <code><a
799href= "#XML_ParseBuffer">XML_ParseBuffer</a></code> calls against this
800parser.  Since external entities my refer to other external entities,
801your handler should be prepared to be called recursively.</p>
802
803<h3>Parsing DTDs</h3>
804
805<p>In order to parse parameter entities, before starting the parse,
806you must call <code><a href= "#XML_SetParamEntityParsing"
807>XML_SetParamEntityParsing</a></code> with one of the following
808arguments:</p>
809<dl>
810<dt><code>XML_PARAM_ENTITY_PARSING_NEVER</code></dt>
811<dd>Don't parse parameter entities or the external subset</dd>
812<dt><code>XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE</code></dt>
813<dd>Parse parameter entities and the external subset unless
814<code>standalone</code> was set to "yes" in the XML declaration.</dd>
815<dt><code>XML_PARAM_ENTITY_PARSING_ALWAYS</code></dt>
816<dd>Always parse parameter entities and the external subset</dd>
817</dl>
818
819<p>In order to read an external DTD, you also have to set an external
820entity reference handler as described above.</p>
821
822<h3 id="stop-resume">Temporarily Stopping Parsing</h3>
823
824<p>Expat 1.95.8 introduces a new feature: its now possible to stop
825parsing temporarily from within a handler function, even if more data
826has already been passed into the parser.  Applications for this
827include</p>
828
829<ul>
830  <li>Supporting the <a href= "https://www.w3.org/TR/xinclude/"
831  >XInclude</a> specification.</li>
832
833  <li>Delaying further processing until additional information is
834  available from some other source.</li>
835
836  <li>Adjusting processor load as task priorities shift within an
837  application.</li>
838
839  <li>Stopping parsing completely (simply free or reset the parser
840  instead of resuming in the outer parsing loop).  This can be useful
841  if an application-domain error is found in the XML being parsed or if
842  the result of the parse is determined not to be useful after
843  all.</li>
844</ul>
845
846<p>To take advantage of this feature, the main parsing loop of an
847application needs to support this specifically.  It cannot be
848supported with a parsing loop compatible with Expat 1.95.7 or
849earlier (though existing loops will continue to work without
850supporting the stop/resume feature).</p>
851
852<p>An application that uses this feature for a single parser will have
853the rough structure (in pseudo-code):</p>
854
855<pre class="pseudocode">
856fd = open_input()
857p = create_parser()
858
859if parse_xml(p, fd) {
860  /* suspended */
861
862  int suspended = 1;
863
864  while (suspended) {
865    do_something_else()
866    if ready_to_resume() {
867      suspended = continue_parsing(p, fd);
868    }
869  }
870}
871</pre>
872
873<p>An application that may resume any of several parsers based on
874input (either from the XML being parsed or some other source) will
875certainly have more interesting control structures.</p>
876
877<p>This C function could be used for the <code>parse_xml</code>
878function mentioned in the pseudo-code above:</p>
879
880<pre class="eg">
881#define BUFF_SIZE 10240
882
883/* Parse a document from the open file descriptor 'fd' until the parse
884   is complete (the document has been completely parsed, or there's
885   been an error), or the parse is stopped.  Return non-zero when
886   the parse is merely suspended.
887*/
888int
889parse_xml(XML_Parser p, int fd)
890{
891  for (;;) {
892    int last_chunk;
893    int bytes_read;
894    enum XML_Status status;
895
896    void *buff = XML_GetBuffer(p, BUFF_SIZE);
897    if (buff == NULL) {
898      /* handle error... */
899      return 0;
900    }
901    bytes_read = read(fd, buff, BUFF_SIZE);
902    if (bytes_read &lt; 0) {
903      /* handle error... */
904      return 0;
905    }
906    status = XML_ParseBuffer(p, bytes_read, bytes_read == 0);
907    switch (status) {
908      case XML_STATUS_ERROR:
909        /* handle error... */
910        return 0;
911      case XML_STATUS_SUSPENDED:
912        return 1;
913    }
914    if (bytes_read == 0)
915      return 0;
916  }
917}
918</pre>
919
920<p>The corresponding <code>continue_parsing</code> function is
921somewhat simpler, since it only need deal with the return code from
922<code><a href= "#XML_ResumeParser">XML_ResumeParser</a></code>; it can
923delegate the input handling to the <code>parse_xml</code>
924function:</p>
925
926<pre class="eg">
927/* Continue parsing a document which had been suspended.  The 'p' and
928   'fd' arguments are the same as passed to parse_xml().  Return
929   non-zero when the parse is suspended.
930*/
931int
932continue_parsing(XML_Parser p, int fd)
933{
934  enum XML_Status status = XML_ResumeParser(p);
935  switch (status) {
936    case XML_STATUS_ERROR:
937      /* handle error... */
938      return 0;
939    case XML_ERROR_NOT_SUSPENDED:
940      /* handle error... */
941      return 0;.
942    case XML_STATUS_SUSPENDED:
943      return 1;
944  }
945  return parse_xml(p, fd);
946}
947</pre>
948
949<p>Now that we've seen what a mess the top-level parsing loop can
950become, what have we gained?  Very simply, we can now use the <code><a
951href= "#XML_StopParser" >XML_StopParser</a></code> function to stop
952parsing, without having to go to great lengths to avoid additional
953processing that we're expecting to ignore.  As a bonus, we get to stop
954parsing <em>temporarily</em>, and come back to it when we're
955ready.</p>
956
957<p>To stop parsing from a handler function, use the <code><a href=
958"#XML_StopParser" >XML_StopParser</a></code> function.  This function
959takes two arguments; the parser being stopped and a flag indicating
960whether the parse can be resumed in the future.</p>
961
962<!-- XXX really need more here -->
963
964
965<hr />
966<!-- ================================================================ -->
967
968<h2><a name="reference">Expat Reference</a></h2>
969
970<h3><a name="creation">Parser Creation</a></h3>
971
972<h4 id="XML_ParserCreate">XML_ParserCreate</h4>
973<pre class="fcndec">
974XML_Parser XMLCALL
975XML_ParserCreate(const XML_Char *encoding);
976</pre>
977<div class="fcndef">
978<p>
979Construct a new parser. If encoding is non-<code>NULL</code>, it specifies a
980character encoding to use for the document. This overrides the document
981encoding declaration. There are four built-in encodings:
982</p>
983<ul>
984<li>US-ASCII</li>
985<li>UTF-8</li>
986<li>UTF-16</li>
987<li>ISO-8859-1</li>
988</ul>
989<p>
990Any other value will invoke a call to the UnknownEncodingHandler.
991</p>
992</div>
993
994<h4 id="XML_ParserCreateNS">XML_ParserCreateNS</h4>
995<pre class="fcndec">
996XML_Parser XMLCALL
997XML_ParserCreateNS(const XML_Char *encoding,
998                   XML_Char sep);
999</pre>
1000<div class="fcndef">
1001Constructs a new parser that has namespace processing in effect. Namespace
1002expanded element names and attribute names are returned as a concatenation
1003of the namespace URI, <em>sep</em>, and the local part of the name. This
1004means that you should pick a character for <em>sep</em> that can't be part
1005of an URI. Since Expat does not check namespace URIs for conformance, the
1006only safe choice for a namespace separator is a character that is illegal
1007in XML. For instance, <code>'\xFF'</code> is not legal in UTF-8, and
1008<code>'\xFFFF'</code> is not legal in UTF-16. There is a special case when
1009<em>sep</em> is the null character <code>'\0'</code>: the namespace URI and
1010the local part will be concatenated without any separator - this is intended
1011to support RDF processors. It is a programming error to use the null separator
1012with <a href= "#XML_SetReturnNSTriplet">namespace triplets</a>.</div>
1013
1014<p><strong>Note:</strong>
1015Expat does not validate namespace URIs (beyond encoding)
1016against RFC 3986 today (and is not required to do so with regard to
1017the XML 1.0 namespaces specification) but it may start doing that
1018in future releases.  Before that, an application using Expat must
1019be ready to receive namespace URIs containing non-URI characters.
1020</p>
1021
1022<h4 id="XML_ParserCreate_MM">XML_ParserCreate_MM</h4>
1023<pre class="fcndec">
1024XML_Parser XMLCALL
1025XML_ParserCreate_MM(const XML_Char *encoding,
1026                    const XML_Memory_Handling_Suite *ms,
1027		    const XML_Char *sep);
1028</pre>
1029<pre class="signature">
1030typedef struct {
1031  void *(XMLCALL *malloc_fcn)(size_t size);
1032  void *(XMLCALL *realloc_fcn)(void *ptr, size_t size);
1033  void (XMLCALL *free_fcn)(void *ptr);
1034} XML_Memory_Handling_Suite;
1035</pre>
1036<div class="fcndef">
1037<p>Construct a new parser using the suite of memory handling functions
1038specified in <code>ms</code>. If <code>ms</code> is <code>NULL</code>, then use the
1039standard set of memory management functions. If <code>sep</code> is
1040non-<code>NULL</code>, then namespace processing is enabled in the created parser
1041and the character pointed at by sep is used as the separator between
1042the namespace URI and the local part of the name.</p>
1043</div>
1044
1045<h4 id="XML_ExternalEntityParserCreate">XML_ExternalEntityParserCreate</h4>
1046<pre class="fcndec">
1047XML_Parser XMLCALL
1048XML_ExternalEntityParserCreate(XML_Parser p,
1049                               const XML_Char *context,
1050                               const XML_Char *encoding);
1051</pre>
1052<div class="fcndef">
1053Construct a new <code>XML_Parser</code> object for parsing an external
1054general entity. Context is the context argument passed in a call to a
1055ExternalEntityRefHandler. Other state information such as handlers,
1056user data, namespace processing is inherited from the parser passed as
1057the 1st argument. So you shouldn't need to call any of the behavior
1058changing functions on this parser (unless you want it to act
1059differently than the parent parser).
1060</div>
1061
1062<h4 id="XML_ParserFree">XML_ParserFree</h4>
1063<pre class="fcndec">
1064void XMLCALL
1065XML_ParserFree(XML_Parser p);
1066</pre>
1067<div class="fcndef">
1068Free memory used by the parser. Your application is responsible for
1069freeing any memory associated with <a href="#userdata">user data</a>.
1070</div>
1071
1072<h4 id="XML_ParserReset">XML_ParserReset</h4>
1073<pre class="fcndec">
1074XML_Bool XMLCALL
1075XML_ParserReset(XML_Parser p,
1076                const XML_Char *encoding);
1077</pre>
1078<div class="fcndef">
1079Clean up the memory structures maintained by the parser so that it may
1080be used again.  After this has been called, <code>parser</code> is
1081ready to start parsing a new document.  All handlers are cleared from
1082the parser, except for the unknownEncodingHandler.  The parser's external
1083state is re-initialized except for the values of ns and ns_triplets.
1084This function may not be used on a parser created using <code><a href=
1085"#XML_ExternalEntityParserCreate" >XML_ExternalEntityParserCreate</a
1086></code>; it will return <code>XML_FALSE</code> in that case.  Returns
1087<code>XML_TRUE</code> on success.  Your application is responsible for
1088dealing with any memory associated with <a href="#userdata">user data</a>.
1089</div>
1090
1091<h3><a name="parsing">Parsing</a></h3>
1092
1093<p>To state the obvious: the three parsing functions <code><a href=
1094"#XML_Parse" >XML_Parse</a></code>, <code><a href= "#XML_ParseBuffer">
1095XML_ParseBuffer</a></code> and <code><a href= "#XML_GetBuffer">
1096XML_GetBuffer</a></code> must not be called from within a handler
1097unless they operate on a separate parser instance, that is, one that
1098did not call the handler. For example, it is OK to call the parsing
1099functions from within an <code>XML_ExternalEntityRefHandler</code>,
1100if they apply to the parser created by
1101<code><a href= "#XML_ExternalEntityParserCreate"
1102>XML_ExternalEntityParserCreate</a></code>.</p>
1103
1104<p>Note: The <code>len</code> argument passed to these functions
1105should be considerably less than the maximum value for an integer,
1106as it could create an integer overflow situation if the added
1107lengths of a buffer and the unprocessed portion of the previous buffer
1108exceed the maximum integer value. Input data at the end of a buffer
1109will remain unprocessed if it is part of an XML token for which the
1110end is not part of that buffer.</p>
1111
1112<p><a name="isFinal"></a>The application <em>must</em> make a concluding
1113<code><a href="#XML_Parse">XML_Parse</a></code> or
1114<code><a href="#XML_ParseBuffer">XML_ParseBuffer</a></code> call
1115with <code>isFinal</code> set to <code>XML_TRUE</code>.</p>
1116
1117<h4 id="XML_Parse">XML_Parse</h4>
1118<pre class="fcndec">
1119enum XML_Status XMLCALL
1120XML_Parse(XML_Parser p,
1121          const char *s,
1122          int len,
1123          int isFinal);
1124</pre>
1125<pre class="signature">
1126enum XML_Status {
1127  XML_STATUS_ERROR = 0,
1128  XML_STATUS_OK = 1
1129};
1130</pre>
1131<div class="fcndef">
1132<p>
1133Parse some more of the document. The string <code>s</code> is a buffer
1134containing part (or perhaps all) of the document. The number of bytes of s
1135that are part of the document is indicated by <code>len</code>. This means
1136that <code>s</code> doesn't have to be null-terminated. It also means that
1137if <code>len</code> is larger than the number of bytes in the block of
1138memory that <code>s</code> points at, then a memory fault is likely.
1139Negative values for <code>len</code> are rejected since Expat 2.2.1.
1140The
1141<code>isFinal</code> parameter informs the parser that this is the last
1142piece of the document. Frequently, the last piece is empty (i.e.
1143<code>len</code> is zero.)
1144</p>
1145
1146<p>
1147If a parse error occurred, it returns <code>XML_STATUS_ERROR</code>.
1148Otherwise it returns <code>XML_STATUS_OK</code> value.
1149Note that regardless of the return value, there is no guarantee that all
1150provided input has been parsed; only after <a href="#isFinal">the
1151concluding call</a> will all handler callbacks and parsing errors have
1152happened.
1153</p>
1154
1155<p>
1156Simplified, <code>XML_Parse</code> can be considered a convenience wrapper
1157that is pairing calls
1158to <code><a href="#XML_GetBuffer">XML_GetBuffer</a></code>
1159and <code><a href="#XML_ParseBuffer">XML_ParseBuffer</a></code>
1160(when Expat is built with macro <code>XML_CONTEXT_BYTES</code>
1161defined to a positive value, which is both common and default).
1162<code>XML_Parse</code> is then functionally equivalent to calling
1163<code><a href="#XML_GetBuffer">XML_GetBuffer</a></code>,
1164<code>memcpy</code>, and
1165<code><a href="#XML_ParseBuffer">XML_ParseBuffer</a></code>.
1166</p>
1167
1168<p>
1169To avoid double copying of the input, direct use of functions
1170<code><a href="#XML_GetBuffer">XML_GetBuffer</a></code> and
1171<code><a href="#XML_ParseBuffer">XML_ParseBuffer</a></code> is advised
1172for most production use, e.g.
1173if you're using <code>read</code> or similar functionality to fill your
1174buffers, fill directly into the buffer from
1175<code><a href="#XML_GetBuffer">XML_GetBuffer</a></code>,
1176then parse with <code><a href="#XML_ParseBuffer">XML_ParseBuffer</a></code>.
1177</p>
1178</div>
1179
1180<h4 id="XML_ParseBuffer">XML_ParseBuffer</h4>
1181<pre class="fcndec">
1182enum XML_Status XMLCALL
1183XML_ParseBuffer(XML_Parser p,
1184                int len,
1185                int isFinal);
1186</pre>
1187<div class="fcndef">
1188<p>
1189This is just like <code><a href= "#XML_Parse" >XML_Parse</a></code>,
1190except in this case Expat provides the buffer.  By obtaining the
1191buffer from Expat with the <code><a href= "#XML_GetBuffer"
1192>XML_GetBuffer</a></code> function, the application can avoid double
1193copying of the input.
1194</p>
1195
1196<p>
1197Negative values for <code>len</code> are rejected since Expat 2.6.3.
1198</p>
1199</div>
1200
1201<h4 id="XML_GetBuffer">XML_GetBuffer</h4>
1202<pre class="fcndec">
1203void * XMLCALL
1204XML_GetBuffer(XML_Parser p,
1205              int len);
1206</pre>
1207<div class="fcndef">
1208Obtain a buffer of size <code>len</code> to read a piece of the document
1209into. A <code>NULL</code> value is returned if Expat can't allocate enough memory for
1210this buffer. A <code>NULL</code> value may also be returned if <code>len</code> is zero.
1211This has to be called prior to every call to
1212<code><a href= "#XML_ParseBuffer" >XML_ParseBuffer</a></code>. A
1213typical use would look like this:
1214
1215<pre class="eg">
1216for (;;) {
1217  int bytes_read;
1218  void *buff = XML_GetBuffer(p, BUFF_SIZE);
1219  if (buff == NULL) {
1220    /* handle error */
1221  }
1222
1223  bytes_read = read(docfd, buff, BUFF_SIZE);
1224  if (bytes_read &lt; 0) {
1225    /* handle error */
1226  }
1227
1228  if (! XML_ParseBuffer(p, bytes_read, bytes_read == 0)) {
1229    /* handle parse error */
1230  }
1231
1232  if (bytes_read == 0)
1233    break;
1234}
1235</pre>
1236</div>
1237
1238<h4 id="XML_StopParser">XML_StopParser</h4>
1239<pre class="fcndec">
1240enum XML_Status XMLCALL
1241XML_StopParser(XML_Parser p,
1242               XML_Bool resumable);
1243</pre>
1244<div class="fcndef">
1245
1246<p>Stops parsing, causing <code><a href= "#XML_Parse"
1247>XML_Parse</a></code> or <code><a href= "#XML_ParseBuffer"
1248>XML_ParseBuffer</a></code> to return.  Must be called from within a
1249call-back handler, except when aborting (when <code>resumable</code>
1250is <code>XML_FALSE</code>) an already suspended parser.  Some
1251call-backs may still follow because they would otherwise get
1252lost, including</p>
1253<ul>
1254  <li> the end element handler for empty elements when stopped in the
1255       start element handler,</li>
1256  <li> the end namespace declaration handler when stopped in the end
1257       element handler,</li>
1258  <li> the character data handler when stopped in the character data handler
1259       while making multiple call-backs on a contiguous chunk of characters,</li>
1260</ul>
1261<p>and possibly others.</p>
1262
1263<p>This can be called from most handlers, including DTD related
1264call-backs, except when parsing an external parameter entity and
1265<code>resumable</code> is <code>XML_TRUE</code>.  Returns
1266<code>XML_STATUS_OK</code> when successful,
1267<code>XML_STATUS_ERROR</code> otherwise.  The possible error codes
1268are:</p>
1269<dl>
1270  <dt><code>XML_ERROR_NOT_STARTED</code></dt>
1271  <dd>
1272    when stopping or suspending a parser before it has started,
1273    added in Expat 2.6.4.
1274  </dd>
1275  <dt><code>XML_ERROR_SUSPENDED</code></dt>
1276  <dd>when suspending an already suspended parser.</dd>
1277  <dt><code>XML_ERROR_FINISHED</code></dt>
1278  <dd>when the parser has already finished.</dd>
1279  <dt><code>XML_ERROR_SUSPEND_PE</code></dt>
1280  <dd>when suspending while parsing an external PE.</dd>
1281</dl>
1282
1283<p>Since the stop/resume feature requires application support in the
1284outer parsing loop, it is an error to call this function for a parser
1285not being handled appropriately; see <a href= "#stop-resume"
1286>Temporarily Stopping Parsing</a> for more information.</p>
1287
1288<p>When <code>resumable</code> is <code>XML_TRUE</code> then parsing
1289is <em>suspended</em>, that is, <code><a href= "#XML_Parse"
1290>XML_Parse</a></code> and <code><a href= "#XML_ParseBuffer"
1291>XML_ParseBuffer</a></code> return <code>XML_STATUS_SUSPENDED</code>.
1292Otherwise, parsing is <em>aborted</em>, that is, <code><a href=
1293"#XML_Parse" >XML_Parse</a></code> and <code><a href=
1294"#XML_ParseBuffer" >XML_ParseBuffer</a></code> return
1295<code>XML_STATUS_ERROR</code> with error code
1296<code>XML_ERROR_ABORTED</code>.</p>
1297
1298<p><strong>Note:</strong>
1299This will be applied to the current parser instance only, that is, if
1300there is a parent parser then it will continue parsing when the
1301external entity reference handler returns.  It is up to the
1302implementation of that handler to call <code><a href=
1303"#XML_StopParser" >XML_StopParser</a></code> on the parent parser
1304(recursively), if one wants to stop parsing altogether.</p>
1305
1306<p>When suspended, parsing can be resumed by calling <code><a href=
1307"#XML_ResumeParser" >XML_ResumeParser</a></code>.</p>
1308
1309<p>New in Expat 1.95.8.</p>
1310</div>
1311
1312<h4 id="XML_ResumeParser">XML_ResumeParser</h4>
1313<pre class="fcndec">
1314enum XML_Status XMLCALL
1315XML_ResumeParser(XML_Parser p);
1316</pre>
1317<div class="fcndef">
1318<p>Resumes parsing after it has been suspended with <code><a href=
1319"#XML_StopParser" >XML_StopParser</a></code>.  Must not be called from
1320within a handler call-back.  Returns same status codes as <code><a
1321href= "#XML_Parse">XML_Parse</a></code> or <code><a href=
1322"#XML_ParseBuffer" >XML_ParseBuffer</a></code>.  An additional error
1323code, <code>XML_ERROR_NOT_SUSPENDED</code>, will be returned if the
1324parser was not currently suspended.</p>
1325
1326<p><strong>Note:</strong>
1327This must be called on the most deeply nested child parser instance
1328first, and on its parent parser only after the child parser has
1329finished, to be applied recursively until the document entity's parser
1330is restarted.  That is, the parent parser will not resume by itself
1331and it is up to the application to call <code><a href=
1332"#XML_ResumeParser" >XML_ResumeParser</a></code> on it at the
1333appropriate moment.</p>
1334
1335<p>New in Expat 1.95.8.</p>
1336</div>
1337
1338<h4 id="XML_GetParsingStatus">XML_GetParsingStatus</h4>
1339<pre class="fcndec">
1340void XMLCALL
1341XML_GetParsingStatus(XML_Parser p,
1342                     XML_ParsingStatus *status);
1343</pre>
1344<pre class="signature">
1345enum XML_Parsing {
1346  XML_INITIALIZED,
1347  XML_PARSING,
1348  XML_FINISHED,
1349  XML_SUSPENDED
1350};
1351
1352typedef struct {
1353  enum XML_Parsing parsing;
1354  XML_Bool finalBuffer;
1355} XML_ParsingStatus;
1356</pre>
1357<div class="fcndef">
1358<p>Returns status of parser with respect to being initialized,
1359parsing, finished, or suspended, and whether the final buffer is being
1360processed.  The <code>status</code> parameter <em>must not</em> be
1361<code>NULL</code>.</p>
1362
1363<p>New in Expat 1.95.8.</p>
1364</div>
1365
1366
1367<h3><a name="setting">Handler Setting</a></h3>
1368
1369<p>Although handlers are typically set prior to parsing and left alone, an
1370application may choose to set or change the handler for a parsing event
1371while the parse is in progress. For instance, your application may choose
1372to ignore all text not descended from a <code>para</code> element. One
1373way it could do this is to set the character handler when a para start tag
1374is seen, and unset it for the corresponding end tag.</p>
1375
1376<p>A handler may be <em>unset</em> by providing a <code>NULL</code> pointer to the
1377appropriate handler setter. None of the handler setting functions have
1378a return value.</p>
1379
1380<p>Your handlers will be receiving strings in arrays of type
1381<code>XML_Char</code>. This type is conditionally defined in expat.h as
1382either <code>char</code>, <code>wchar_t</code> or <code>unsigned short</code>.
1383The former implies UTF-8 encoding, the latter two imply UTF-16 encoding.
1384Note that you'll receive them in this form independent of the original
1385encoding of the document.</p>
1386
1387<div class="handler">
1388<h4 id="XML_SetStartElementHandler">XML_SetStartElementHandler</h4>
1389<pre class="setter">
1390void XMLCALL
1391XML_SetStartElementHandler(XML_Parser p,
1392                           XML_StartElementHandler start);
1393</pre>
1394<pre class="signature">
1395typedef void
1396(XMLCALL *XML_StartElementHandler)(void *userData,
1397                                   const XML_Char *name,
1398                                   const XML_Char **atts);
1399</pre>
1400<p>Set handler for start (and empty) tags. Attributes are passed to the start
1401handler as a pointer to a vector of char pointers. Each attribute seen in
1402a start (or empty) tag occupies 2 consecutive places in this vector: the
1403attribute name followed by the attribute value. These pairs are terminated
1404by a <code>NULL</code> pointer.</p>
1405<p>Note that an empty tag generates a call to both start and end handlers
1406(in that order).</p>
1407</div>
1408
1409<div class="handler">
1410<h4 id="XML_SetEndElementHandler">XML_SetEndElementHandler</h4>
1411<pre class="setter">
1412void XMLCALL
1413XML_SetEndElementHandler(XML_Parser p,
1414                         XML_EndElementHandler);
1415</pre>
1416<pre class="signature">
1417typedef void
1418(XMLCALL *XML_EndElementHandler)(void *userData,
1419                                 const XML_Char *name);
1420</pre>
1421<p>Set handler for end (and empty) tags. As noted above, an empty tag
1422generates a call to both start and end handlers.</p>
1423</div>
1424
1425<div class="handler">
1426<h4 id="XML_SetElementHandler">XML_SetElementHandler</h4>
1427<pre class="setter">
1428void XMLCALL
1429XML_SetElementHandler(XML_Parser p,
1430                      XML_StartElementHandler start,
1431                      XML_EndElementHandler end);
1432</pre>
1433<p>Set handlers for start and end tags with one call.</p>
1434</div>
1435
1436<div class="handler">
1437<h4 id="XML_SetCharacterDataHandler">XML_SetCharacterDataHandler</h4>
1438<pre class="setter">
1439void XMLCALL
1440XML_SetCharacterDataHandler(XML_Parser p,
1441                            XML_CharacterDataHandler charhndl)
1442</pre>
1443<pre class="signature">
1444typedef void
1445(XMLCALL *XML_CharacterDataHandler)(void *userData,
1446                                    const XML_Char *s,
1447                                    int len);
1448</pre>
1449<p>Set a text handler. The string your handler receives
1450is <em>NOT null-terminated</em>. You have to use the length argument
1451to deal with the end of the string. A single block of contiguous text
1452free of markup may still result in a sequence of calls to this handler.
1453In other words, if you're searching for a pattern in the text, it may
1454be split across calls to this handler. Note: Setting this handler to <code>NULL</code>
1455may <em>NOT immediately</em> terminate call-backs if the parser is currently
1456processing such a single block of contiguous markup-free text, as the parser
1457will continue calling back until the end of the block is reached.</p>
1458</div>
1459
1460<div class="handler">
1461<h4 id="XML_SetProcessingInstructionHandler">XML_SetProcessingInstructionHandler</h4>
1462<pre class="setter">
1463void XMLCALL
1464XML_SetProcessingInstructionHandler(XML_Parser p,
1465                                    XML_ProcessingInstructionHandler proc)
1466</pre>
1467<pre class="signature">
1468typedef void
1469(XMLCALL *XML_ProcessingInstructionHandler)(void *userData,
1470                                            const XML_Char *target,
1471                                            const XML_Char *data);
1472
1473</pre>
1474<p>Set a handler for processing instructions. The target is the first word
1475in the processing instruction. The data is the rest of the characters in
1476it after skipping all whitespace after the initial word.</p>
1477</div>
1478
1479<div class="handler">
1480<h4 id="XML_SetCommentHandler">XML_SetCommentHandler</h4>
1481<pre class="setter">
1482void XMLCALL
1483XML_SetCommentHandler(XML_Parser p,
1484                      XML_CommentHandler cmnt)
1485</pre>
1486<pre class="signature">
1487typedef void
1488(XMLCALL *XML_CommentHandler)(void *userData,
1489                              const XML_Char *data);
1490</pre>
1491<p>Set a handler for comments. The data is all text inside the comment
1492delimiters.</p>
1493</div>
1494
1495<div class="handler">
1496<h4 id="XML_SetStartCdataSectionHandler">XML_SetStartCdataSectionHandler</h4>
1497<pre class="setter">
1498void XMLCALL
1499XML_SetStartCdataSectionHandler(XML_Parser p,
1500                                XML_StartCdataSectionHandler start);
1501</pre>
1502<pre class="signature">
1503typedef void
1504(XMLCALL *XML_StartCdataSectionHandler)(void *userData);
1505</pre>
1506<p>Set a handler that gets called at the beginning of a CDATA section.</p>
1507</div>
1508
1509<div class="handler">
1510<h4 id="XML_SetEndCdataSectionHandler">XML_SetEndCdataSectionHandler</h4>
1511<pre class="setter">
1512void XMLCALL
1513XML_SetEndCdataSectionHandler(XML_Parser p,
1514                              XML_EndCdataSectionHandler end);
1515</pre>
1516<pre class="signature">
1517typedef void
1518(XMLCALL *XML_EndCdataSectionHandler)(void *userData);
1519</pre>
1520<p>Set a handler that gets called at the end of a CDATA section.</p>
1521</div>
1522
1523<div class="handler">
1524<h4 id="XML_SetCdataSectionHandler">XML_SetCdataSectionHandler</h4>
1525<pre class="setter">
1526void XMLCALL
1527XML_SetCdataSectionHandler(XML_Parser p,
1528                           XML_StartCdataSectionHandler start,
1529                           XML_EndCdataSectionHandler end)
1530</pre>
1531<p>Sets both CDATA section handlers with one call.</p>
1532</div>
1533
1534<div class="handler">
1535<h4 id="XML_SetDefaultHandler">XML_SetDefaultHandler</h4>
1536<pre class="setter">
1537void XMLCALL
1538XML_SetDefaultHandler(XML_Parser p,
1539                      XML_DefaultHandler hndl)
1540</pre>
1541<pre class="signature">
1542typedef void
1543(XMLCALL *XML_DefaultHandler)(void *userData,
1544                              const XML_Char *s,
1545                              int len);
1546</pre>
1547
1548<p>Sets a handler for any characters in the document which wouldn't
1549otherwise be handled. This includes both data for which no handlers
1550can be set (like some kinds of DTD declarations) and data which could
1551be reported but which currently has no handler set.  The characters
1552are passed exactly as they were present in the XML document except
1553that they will be encoded in UTF-8 or UTF-16. Line boundaries are not
1554normalized. Note that a byte order mark character is not passed to the
1555default handler. There are no guarantees about how characters are
1556divided between calls to the default handler: for example, a comment
1557might be split between multiple calls.  Setting the handler with
1558this call has the side effect of turning off expansion of references
1559to internally defined general entities. Instead these references are
1560passed to the default handler.</p>
1561
1562<p>See also <code><a
1563href="#XML_DefaultCurrent">XML_DefaultCurrent</a></code>.</p>
1564</div>
1565
1566<div class="handler">
1567<h4 id="XML_SetDefaultHandlerExpand">XML_SetDefaultHandlerExpand</h4>
1568<pre class="setter">
1569void XMLCALL
1570XML_SetDefaultHandlerExpand(XML_Parser p,
1571                            XML_DefaultHandler hndl)
1572</pre>
1573<pre class="signature">
1574typedef void
1575(XMLCALL *XML_DefaultHandler)(void *userData,
1576                              const XML_Char *s,
1577                              int len);
1578</pre>
1579<p>This sets a default handler, but doesn't inhibit the expansion of
1580internal entity references.  The entity reference will not be passed
1581to the default handler.</p>
1582
1583<p>See also <code><a
1584href="#XML_DefaultCurrent">XML_DefaultCurrent</a></code>.</p>
1585</div>
1586
1587<div class="handler">
1588<h4 id="XML_SetExternalEntityRefHandler">XML_SetExternalEntityRefHandler</h4>
1589<pre class="setter">
1590void XMLCALL
1591XML_SetExternalEntityRefHandler(XML_Parser p,
1592                                XML_ExternalEntityRefHandler hndl)
1593</pre>
1594<pre class="signature">
1595typedef int
1596(XMLCALL *XML_ExternalEntityRefHandler)(XML_Parser p,
1597                                        const XML_Char *context,
1598                                        const XML_Char *base,
1599                                        const XML_Char *systemId,
1600                                        const XML_Char *publicId);
1601</pre>
1602<p>Set an external entity reference handler. This handler is also
1603called for processing an external DTD subset if parameter entity parsing
1604is in effect. (See <a href="#XML_SetParamEntityParsing">
1605<code>XML_SetParamEntityParsing</code></a>.)</p>
1606
1607<p>The <code>context</code> parameter specifies the parsing context in
1608the format expected by the <code>context</code> argument to <code><a
1609href="#XML_ExternalEntityParserCreate"
1610>XML_ExternalEntityParserCreate</a></code>.  <code>code</code> is
1611valid only until the handler returns, so if the referenced entity is
1612to be parsed later, it must be copied.  <code>context</code> is <code>NULL</code>
1613only when the entity is a parameter entity, which is how one can
1614differentiate between general and parameter entities.</p>
1615
1616<p>The <code>base</code> parameter is the base to use for relative
1617system identifiers.  It is set by <code><a
1618href="#XML_SetBase">XML_SetBase</a></code> and may be <code>NULL</code>. The
1619<code>publicId</code> parameter is the public id given in the entity
1620declaration and may be <code>NULL</code>.  <code>systemId</code> is the system
1621identifier specified in the entity declaration and is never <code>NULL</code>.</p>
1622
1623<p>There are a couple of ways in which this handler differs from
1624others.  First, this handler returns a status indicator (an
1625integer). <code>XML_STATUS_OK</code> should be returned for successful
1626handling of the external entity reference.  Returning
1627<code>XML_STATUS_ERROR</code> indicates failure, and causes the
1628calling parser to return an
1629<code>XML_ERROR_EXTERNAL_ENTITY_HANDLING</code> error.</p>
1630
1631<p>Second, instead of having the user data as its first argument, it
1632receives the parser that encountered the entity reference. This, along
1633with the context parameter, may be used as arguments to a call to
1634<code><a href= "#XML_ExternalEntityParserCreate"
1635>XML_ExternalEntityParserCreate</a></code>.  Using the returned
1636parser, the body of the external entity can be recursively parsed.</p>
1637
1638<p>Since this handler may be called recursively, it should not be saving
1639information into global or static variables.</p>
1640</div>
1641
1642<h4 id="XML_SetExternalEntityRefHandlerArg">XML_SetExternalEntityRefHandlerArg</h4>
1643<pre class="fcndec">
1644void XMLCALL
1645XML_SetExternalEntityRefHandlerArg(XML_Parser p,
1646                                   void *arg)
1647</pre>
1648<div class="fcndef">
1649<p>Set the argument passed to the ExternalEntityRefHandler.  If
1650<code>arg</code> is not <code>NULL</code>, it is the new value passed to the
1651handler set using <code><a href="#XML_SetExternalEntityRefHandler"
1652>XML_SetExternalEntityRefHandler</a></code>; if <code>arg</code> is
1653<code>NULL</code>, the argument passed to the handler function will be the parser
1654object itself.</p>
1655
1656<p><strong>Note:</strong>
1657The type of <code>arg</code> and the type of the first argument to the
1658ExternalEntityRefHandler do not match.  This function takes a
1659<code>void *</code> to be passed to the handler, while the handler
1660accepts an <code>XML_Parser</code>.  This is a historical accident,
1661but will not be corrected before Expat 2.0 (at the earliest) to avoid
1662causing compiler warnings for code that's known to work with this
1663API.  It is the responsibility of the application code to know the
1664actual type of the argument passed to the handler and to manage it
1665properly.</p>
1666</div>
1667
1668<div class="handler">
1669<h4 id="XML_SetSkippedEntityHandler">XML_SetSkippedEntityHandler</h4>
1670<pre class="setter">
1671void XMLCALL
1672XML_SetSkippedEntityHandler(XML_Parser p,
1673                            XML_SkippedEntityHandler handler)
1674</pre>
1675<pre class="signature">
1676typedef void
1677(XMLCALL *XML_SkippedEntityHandler)(void *userData,
1678                                    const XML_Char *entityName,
1679                                    int is_parameter_entity);
1680</pre>
1681<p>Set a skipped entity handler. This is called in two situations:</p>
1682<ol>
1683   <li>An entity reference is encountered for which no declaration
1684       has been read <em>and</em> this is not an error.</li>
1685   <li>An internal entity reference is read, but not expanded, because
1686       <a href="#XML_SetDefaultHandler"><code>XML_SetDefaultHandler</code></a>
1687	   has been called.</li>
1688</ol>
1689<p>The <code>is_parameter_entity</code> argument will be non-zero for
1690a parameter entity and zero for a general entity.</p> <p>Note: Skipped
1691parameter entities in declarations and skipped general entities in
1692attribute values cannot be reported, because the event would be out of
1693sync with the reporting of the declarations or attribute values</p>
1694</div>
1695
1696<div class="handler">
1697<h4 id="XML_SetUnknownEncodingHandler">XML_SetUnknownEncodingHandler</h4>
1698<pre class="setter">
1699void XMLCALL
1700XML_SetUnknownEncodingHandler(XML_Parser p,
1701                              XML_UnknownEncodingHandler enchandler,
1702			      void *encodingHandlerData)
1703</pre>
1704<pre class="signature">
1705typedef int
1706(XMLCALL *XML_UnknownEncodingHandler)(void *encodingHandlerData,
1707                                      const XML_Char *name,
1708                                      XML_Encoding *info);
1709
1710typedef struct {
1711  int map[256];
1712  void *data;
1713  int (XMLCALL *convert)(void *data, const char *s);
1714  void (XMLCALL *release)(void *data);
1715} XML_Encoding;
1716</pre>
1717<p>Set a handler to deal with encodings other than the <a
1718href="#builtin_encodings">built in set</a>. This should be done before
1719<code><a href= "#XML_Parse" >XML_Parse</a></code> or <code><a href=
1720"#XML_ParseBuffer" >XML_ParseBuffer</a></code> have been called on the
1721given parser.</p> <p>If the handler knows how to deal with an encoding
1722with the given name, it should fill in the <code>info</code> data
1723structure and return <code>XML_STATUS_OK</code>. Otherwise it
1724should return <code>XML_STATUS_ERROR</code>. The handler will be called
1725at most once per parsed (external) entity. The optional application
1726data pointer <code>encodingHandlerData</code> will be passed back to
1727the handler.</p>
1728
1729<p>The map array contains information for every possible leading
1730byte in a byte sequence. If the corresponding value is &gt;= 0, then it's
1731a single byte sequence and the byte encodes that Unicode value. If the
1732value is -1, then that byte is invalid as the initial byte in a sequence.
1733If the value is -n, where n is an integer &gt; 1, then n is the number of
1734bytes in the sequence and the actual conversion is accomplished by a
1735call to the function pointed at by convert. This function may return -1
1736if the sequence itself is invalid. The convert pointer may be <code>NULL</code> if
1737there are only single byte codes. The data parameter passed to the convert
1738function is the data pointer from <code>XML_Encoding</code>. The
1739string s is <em>NOT</em> null-terminated and points at the sequence of
1740bytes to be converted.</p>
1741
1742<p>The function pointed at by <code>release</code> is called by the
1743parser when it is finished with the encoding. It may be <code>NULL</code>.</p>
1744</div>
1745
1746<div class="handler">
1747<h4 id="XML_SetStartNamespaceDeclHandler">XML_SetStartNamespaceDeclHandler</h4>
1748<pre class="setter">
1749void XMLCALL
1750XML_SetStartNamespaceDeclHandler(XML_Parser p,
1751			         XML_StartNamespaceDeclHandler start);
1752</pre>
1753<pre class="signature">
1754typedef void
1755(XMLCALL *XML_StartNamespaceDeclHandler)(void *userData,
1756                                         const XML_Char *prefix,
1757                                         const XML_Char *uri);
1758</pre>
1759<p>Set a handler to be called when a namespace is declared. Namespace
1760declarations occur inside start tags. But the namespace declaration start
1761handler is called before the start tag handler for each namespace declared
1762in that start tag.</p>
1763</div>
1764
1765<div class="handler">
1766<h4 id="XML_SetEndNamespaceDeclHandler">XML_SetEndNamespaceDeclHandler</h4>
1767<pre class="setter">
1768void XMLCALL
1769XML_SetEndNamespaceDeclHandler(XML_Parser p,
1770			       XML_EndNamespaceDeclHandler end);
1771</pre>
1772<pre class="signature">
1773typedef void
1774(XMLCALL *XML_EndNamespaceDeclHandler)(void *userData,
1775                                       const XML_Char *prefix);
1776</pre>
1777<p>Set a handler to be called when leaving the scope of a namespace
1778declaration. This will be called, for each namespace declaration,
1779after the handler for the end tag of the element in which the
1780namespace was declared.</p>
1781</div>
1782
1783<div class="handler">
1784<h4 id="XML_SetNamespaceDeclHandler">XML_SetNamespaceDeclHandler</h4>
1785<pre class="setter">
1786void XMLCALL
1787XML_SetNamespaceDeclHandler(XML_Parser p,
1788                            XML_StartNamespaceDeclHandler start,
1789                            XML_EndNamespaceDeclHandler end)
1790</pre>
1791<p>Sets both namespace declaration handlers with a single call.</p>
1792</div>
1793
1794<div class="handler">
1795<h4 id="XML_SetXmlDeclHandler">XML_SetXmlDeclHandler</h4>
1796<pre class="setter">
1797void XMLCALL
1798XML_SetXmlDeclHandler(XML_Parser p,
1799		      XML_XmlDeclHandler xmldecl);
1800</pre>
1801<pre class="signature">
1802typedef void
1803(XMLCALL *XML_XmlDeclHandler)(void            *userData,
1804                              const XML_Char  *version,
1805                              const XML_Char  *encoding,
1806                              int             standalone);
1807</pre>
1808<p>Sets a handler that is called for XML declarations and also for
1809text declarations discovered in external entities. The way to
1810distinguish is that the <code>version</code> parameter will be <code>NULL</code>
1811for text declarations. The <code>encoding</code> parameter may be <code>NULL</code>
1812for an XML declaration. The <code>standalone</code> argument will
1813contain -1, 0, or 1 indicating respectively that there was no
1814standalone parameter in the declaration, that it was given as no, or
1815that it was given as yes.</p>
1816</div>
1817
1818<div class="handler">
1819<h4 id="XML_SetStartDoctypeDeclHandler">XML_SetStartDoctypeDeclHandler</h4>
1820<pre class="setter">
1821void XMLCALL
1822XML_SetStartDoctypeDeclHandler(XML_Parser p,
1823			       XML_StartDoctypeDeclHandler start);
1824</pre>
1825<pre class="signature">
1826typedef void
1827(XMLCALL *XML_StartDoctypeDeclHandler)(void           *userData,
1828                                       const XML_Char *doctypeName,
1829                                       const XML_Char *sysid,
1830                                       const XML_Char *pubid,
1831                                       int            has_internal_subset);
1832</pre>
1833<p>Set a handler that is called at the start of a DOCTYPE declaration,
1834before any external or internal subset is parsed. Both <code>sysid</code>
1835and <code>pubid</code> may be <code>NULL</code>. The <code>has_internal_subset</code>
1836will be non-zero if the DOCTYPE declaration has an internal subset.</p>
1837</div>
1838
1839<div class="handler">
1840<h4 id="XML_SetEndDoctypeDeclHandler">XML_SetEndDoctypeDeclHandler</h4>
1841<pre class="setter">
1842void XMLCALL
1843XML_SetEndDoctypeDeclHandler(XML_Parser p,
1844			     XML_EndDoctypeDeclHandler end);
1845</pre>
1846<pre class="signature">
1847typedef void
1848(XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
1849</pre>
1850<p>Set a handler that is called at the end of a DOCTYPE declaration,
1851after parsing any external subset.</p>
1852</div>
1853
1854<div class="handler">
1855<h4 id="XML_SetDoctypeDeclHandler">XML_SetDoctypeDeclHandler</h4>
1856<pre class="setter">
1857void XMLCALL
1858XML_SetDoctypeDeclHandler(XML_Parser p,
1859			  XML_StartDoctypeDeclHandler start,
1860			  XML_EndDoctypeDeclHandler end);
1861</pre>
1862<p>Set both doctype handlers with one call.</p>
1863</div>
1864
1865<div class="handler">
1866<h4 id="XML_SetElementDeclHandler">XML_SetElementDeclHandler</h4>
1867<pre class="setter">
1868void XMLCALL
1869XML_SetElementDeclHandler(XML_Parser p,
1870			  XML_ElementDeclHandler eldecl);
1871</pre>
1872<pre class="signature">
1873typedef void
1874(XMLCALL *XML_ElementDeclHandler)(void *userData,
1875                                  const XML_Char *name,
1876                                  XML_Content *model);
1877</pre>
1878<pre class="signature">
1879enum XML_Content_Type {
1880  XML_CTYPE_EMPTY = 1,
1881  XML_CTYPE_ANY,
1882  XML_CTYPE_MIXED,
1883  XML_CTYPE_NAME,
1884  XML_CTYPE_CHOICE,
1885  XML_CTYPE_SEQ
1886};
1887
1888enum XML_Content_Quant {
1889  XML_CQUANT_NONE,
1890  XML_CQUANT_OPT,
1891  XML_CQUANT_REP,
1892  XML_CQUANT_PLUS
1893};
1894
1895typedef struct XML_cp XML_Content;
1896
1897struct XML_cp {
1898  enum XML_Content_Type		type;
1899  enum XML_Content_Quant	quant;
1900  const XML_Char *		name;
1901  unsigned int			numchildren;
1902  XML_Content *			children;
1903};
1904</pre>
1905<p>Sets a handler for element declarations in a DTD. The handler gets
1906called with the name of the element in the declaration and a pointer
1907to a structure that contains the element model. It's the user code's
1908responsibility to free model when finished with it. See <code>
1909<a href="#XML_FreeContentModel">XML_FreeContentModel</a></code>.
1910There is no need to free the model from the handler, it can be kept
1911around and freed at a later stage.</p>
1912
1913<p>The <code>model</code> argument is the root of a tree of
1914<code>XML_Content</code> nodes. If <code>type</code> equals
1915<code>XML_CTYPE_EMPTY</code> or <code>XML_CTYPE_ANY</code>, then
1916<code>quant</code> will be <code>XML_CQUANT_NONE</code>, and the other
1917fields will be zero or <code>NULL</code>.  If <code>type</code> is
1918<code>XML_CTYPE_MIXED</code>, then <code>quant</code> will be
1919<code>XML_CQUANT_NONE</code> or <code>XML_CQUANT_REP</code> and
1920<code>numchildren</code> will contain the number of elements that are
1921allowed to be mixed in and <code>children</code> points to an array of
1922<code>XML_Content</code> structures that will all have type
1923XML_CTYPE_NAME with no quantification.  Only the root node can be type
1924<code>XML_CTYPE_EMPTY</code>, <code>XML_CTYPE_ANY</code>, or
1925<code>XML_CTYPE_MIXED</code>.</p>
1926
1927<p>For type <code>XML_CTYPE_NAME</code>, the <code>name</code> field
1928points to the name and the <code>numchildren</code> and
1929<code>children</code> fields will be zero and <code>NULL</code>. The
1930<code>quant</code> field will indicate any quantifiers placed on the
1931name.</p>
1932
1933<p>Types <code>XML_CTYPE_CHOICE</code> and <code>XML_CTYPE_SEQ</code>
1934indicate a choice or sequence respectively. The
1935<code>numchildren</code> field indicates how many nodes in the choice
1936or sequence and <code>children</code> points to the nodes.</p>
1937</div>
1938
1939<div class="handler">
1940<h4 id="XML_SetAttlistDeclHandler">XML_SetAttlistDeclHandler</h4>
1941<pre class="setter">
1942void XMLCALL
1943XML_SetAttlistDeclHandler(XML_Parser p,
1944                          XML_AttlistDeclHandler attdecl);
1945</pre>
1946<pre class="signature">
1947typedef void
1948(XMLCALL *XML_AttlistDeclHandler)(void           *userData,
1949                                  const XML_Char *elname,
1950                                  const XML_Char *attname,
1951                                  const XML_Char *att_type,
1952                                  const XML_Char *dflt,
1953                                  int            isrequired);
1954</pre>
1955<p>Set a handler for attlist declarations in the DTD. This handler is
1956called for <em>each</em> attribute. So a single attlist declaration
1957with multiple attributes declared will generate multiple calls to this
1958handler. The <code>elname</code> parameter returns the name of the
1959element for which the attribute is being declared. The attribute name
1960is in the <code>attname</code> parameter. The attribute type is in the
1961<code>att_type</code> parameter.  It is the string representing the
1962type in the declaration with whitespace removed.</p>
1963
1964<p>The <code>dflt</code> parameter holds the default value. It will be
1965<code>NULL</code> in the case of "#IMPLIED" or "#REQUIRED" attributes. You can
1966distinguish these two cases by checking the <code>isrequired</code>
1967parameter, which will be true in the case of "#REQUIRED" attributes.
1968Attributes which are "#FIXED" will have also have a true
1969<code>isrequired</code>, but they will have the non-<code>NULL</code> fixed value
1970in the <code>dflt</code> parameter.</p>
1971</div>
1972
1973<div class="handler">
1974<h4 id="XML_SetEntityDeclHandler">XML_SetEntityDeclHandler</h4>
1975<pre class="setter">
1976void XMLCALL
1977XML_SetEntityDeclHandler(XML_Parser p,
1978			 XML_EntityDeclHandler handler);
1979</pre>
1980<pre class="signature">
1981typedef void
1982(XMLCALL *XML_EntityDeclHandler)(void           *userData,
1983                                 const XML_Char *entityName,
1984                                 int            is_parameter_entity,
1985                                 const XML_Char *value,
1986                                 int            value_length,
1987                                 const XML_Char *base,
1988                                 const XML_Char *systemId,
1989                                 const XML_Char *publicId,
1990                                 const XML_Char *notationName);
1991</pre>
1992<p>Sets a handler that will be called for all entity declarations.
1993The <code>is_parameter_entity</code> argument will be non-zero in the
1994case of parameter entities and zero otherwise.</p>
1995
1996<p>For internal entities (<code>&lt;!ENTITY foo "bar"&gt;</code>),
1997<code>value</code> will be non-<code>NULL</code> and <code>systemId</code>,
1998<code>publicId</code>, and <code>notationName</code> will all be <code>NULL</code>.
1999The value string is <em>not</em> null-terminated; the length is
2000provided in the <code>value_length</code> parameter. Do not use
2001<code>value_length</code> to test for internal entities, since it is
2002legal to have zero-length values. Instead check for whether or not
2003<code>value</code> is <code>NULL</code>.</p> <p>The <code>notationName</code>
2004argument will have a non-<code>NULL</code> value only for unparsed entity
2005declarations.</p>
2006</div>
2007
2008<div class="handler">
2009<h4 id="XML_SetUnparsedEntityDeclHandler">XML_SetUnparsedEntityDeclHandler</h4>
2010<pre class="setter">
2011void XMLCALL
2012XML_SetUnparsedEntityDeclHandler(XML_Parser p,
2013                                 XML_UnparsedEntityDeclHandler h)
2014</pre>
2015<pre class="signature">
2016typedef void
2017(XMLCALL *XML_UnparsedEntityDeclHandler)(void *userData,
2018                                         const XML_Char *entityName,
2019                                         const XML_Char *base,
2020                                         const XML_Char *systemId,
2021                                         const XML_Char *publicId,
2022                                         const XML_Char *notationName);
2023</pre>
2024<p>Set a handler that receives declarations of unparsed entities. These
2025are entity declarations that have a notation (NDATA) field:</p>
2026
2027<div id="eg"><pre>
2028&lt;!ENTITY logo SYSTEM "images/logo.gif" NDATA gif&gt;
2029</pre></div>
2030<p>This handler is obsolete and is provided for backwards
2031compatibility.  Use instead <a href= "#XML_SetEntityDeclHandler"
2032>XML_SetEntityDeclHandler</a>.</p>
2033</div>
2034
2035<div class="handler">
2036<h4 id="XML_SetNotationDeclHandler">XML_SetNotationDeclHandler</h4>
2037<pre class="setter">
2038void XMLCALL
2039XML_SetNotationDeclHandler(XML_Parser p,
2040                           XML_NotationDeclHandler h)
2041</pre>
2042<pre class="signature">
2043typedef void
2044(XMLCALL *XML_NotationDeclHandler)(void *userData,
2045                                   const XML_Char *notationName,
2046                                   const XML_Char *base,
2047                                   const XML_Char *systemId,
2048                                   const XML_Char *publicId);
2049</pre>
2050<p>Set a handler that receives notation declarations.</p>
2051</div>
2052
2053<div class="handler">
2054<h4 id="XML_SetNotStandaloneHandler">XML_SetNotStandaloneHandler</h4>
2055<pre class="setter">
2056void XMLCALL
2057XML_SetNotStandaloneHandler(XML_Parser p,
2058                            XML_NotStandaloneHandler h)
2059</pre>
2060<pre class="signature">
2061typedef int
2062(XMLCALL *XML_NotStandaloneHandler)(void *userData);
2063</pre>
2064<p>Set a handler that is called if the document is not "standalone".
2065This happens when there is an external subset or a reference to a
2066parameter entity, but does not have standalone set to "yes" in an XML
2067declaration.  If this handler returns <code>XML_STATUS_ERROR</code>,
2068then the parser will throw an <code>XML_ERROR_NOT_STANDALONE</code>
2069error.</p>
2070</div>
2071
2072<h3><a name="position">Parse position and error reporting functions</a></h3>
2073
2074<p>These are the functions you'll want to call when the parse
2075functions return <code>XML_STATUS_ERROR</code> (a parse error has
2076occurred), although the position reporting functions are useful outside
2077of errors. The position reported is the byte position (in the original
2078document or entity encoding) of the first of the sequence of
2079characters that generated the current event (or the error that caused
2080the parse functions to return <code>XML_STATUS_ERROR</code>.)  The
2081exceptions are callbacks triggered by declarations in the document
2082prologue, in which case they exact position reported is somewhere in the
2083relevant markup, but not necessarily as meaningful as for other
2084events.</p>
2085
2086<p>The position reporting functions are accurate only outside of the
2087DTD.  In other words, they usually return bogus information when
2088called from within a DTD declaration handler.</p>
2089
2090<h4 id="XML_GetErrorCode">XML_GetErrorCode</h4>
2091<pre class="fcndec">
2092enum XML_Error XMLCALL
2093XML_GetErrorCode(XML_Parser p);
2094</pre>
2095<div class="fcndef">
2096Return what type of error has occurred.
2097</div>
2098
2099<h4 id="XML_ErrorString">XML_ErrorString</h4>
2100<pre class="fcndec">
2101const XML_LChar * XMLCALL
2102XML_ErrorString(enum XML_Error code);
2103</pre>
2104<div class="fcndef">
2105Return a string describing the error corresponding to code.
2106The code should be one of the enums that can be returned from
2107<code><a href= "#XML_GetErrorCode" >XML_GetErrorCode</a></code>.
2108</div>
2109
2110<h4 id="XML_GetCurrentByteIndex">XML_GetCurrentByteIndex</h4>
2111<pre class="fcndec">
2112XML_Index XMLCALL
2113XML_GetCurrentByteIndex(XML_Parser p);
2114</pre>
2115<div class="fcndef">
2116Return the byte offset of the position.  This always corresponds to
2117the values returned by <code><a href= "#XML_GetCurrentLineNumber"
2118>XML_GetCurrentLineNumber</a></code> and <code><a href=
2119"#XML_GetCurrentColumnNumber" >XML_GetCurrentColumnNumber</a></code>.
2120</div>
2121
2122<h4 id="XML_GetCurrentLineNumber">XML_GetCurrentLineNumber</h4>
2123<pre class="fcndec">
2124XML_Size XMLCALL
2125XML_GetCurrentLineNumber(XML_Parser p);
2126</pre>
2127<div class="fcndef">
2128Return the line number of the position.  The first line is reported as
2129<code>1</code>.
2130</div>
2131
2132<h4 id="XML_GetCurrentColumnNumber">XML_GetCurrentColumnNumber</h4>
2133<pre class="fcndec">
2134XML_Size XMLCALL
2135XML_GetCurrentColumnNumber(XML_Parser p);
2136</pre>
2137<div class="fcndef">
2138Return the offset, from the beginning of the current line, of
2139the position.
2140</div>
2141
2142<h4 id="XML_GetCurrentByteCount">XML_GetCurrentByteCount</h4>
2143<pre class="fcndec">
2144int XMLCALL
2145XML_GetCurrentByteCount(XML_Parser p);
2146</pre>
2147<div class="fcndef">
2148Return the number of bytes in the current event. Returns
2149<code>0</code> if the event is inside a reference to an internal
2150entity and for the end-tag event for empty element tags (the later can
2151be used to distinguish empty-element tags from empty elements using
2152separate start and end tags).
2153</div>
2154
2155<h4 id="XML_GetInputContext">XML_GetInputContext</h4>
2156<pre class="fcndec">
2157const char * XMLCALL
2158XML_GetInputContext(XML_Parser p,
2159                    int *offset,
2160                    int *size);
2161</pre>
2162<div class="fcndef">
2163
2164<p>Returns the parser's input buffer, sets the integer pointed at by
2165<code>offset</code> to the offset within this buffer of the current
2166parse position, and set the integer pointed at by <code>size</code> to
2167the size of the returned buffer.</p>
2168
2169<p>This should only be called from within a handler during an active
2170parse and the returned buffer should only be referred to from within
2171the handler that made the call. This input buffer contains the
2172untranslated bytes of the input.</p>
2173
2174<p>Only a limited amount of context is kept, so if the event
2175triggering a call spans over a very large amount of input, the actual
2176parse position may be before the beginning of the buffer.</p>
2177
2178<p>If <code>XML_CONTEXT_BYTES</code> is zero, this will always
2179return <code>NULL</code>.</p>
2180</div>
2181
2182<h3><a name="attack-protection">Attack Protection</a><a name="billion-laughs"></a></h3>
2183
2184<h4 id="XML_SetBillionLaughsAttackProtectionMaximumAmplification">XML_SetBillionLaughsAttackProtectionMaximumAmplification</h4>
2185<pre class="fcndec">
2186/* Added in Expat 2.4.0. */
2187XML_Bool XMLCALL
2188XML_SetBillionLaughsAttackProtectionMaximumAmplification(XML_Parser p,
2189                                                         float maximumAmplificationFactor);
2190</pre>
2191<div class="fcndef">
2192  <p>
2193    Sets the maximum tolerated amplification factor
2194    for protection against
2195    <a href="https://en.wikipedia.org/wiki/Billion_laughs_attack">billion laughs attacks</a>
2196    (default: <code>100.0</code>)
2197    of parser <code>p</code> to <code>maximumAmplificationFactor</code>, and
2198    returns <code>XML_TRUE</code> upon success and <code>XML_FALSE</code> upon error.
2199  </p>
2200
2201  The amplification factor is calculated as ..
2202  <pre>
2203    amplification := (direct + indirect) / direct
2204  </pre>
2205  .. while parsing, whereas
2206  <code>direct</code> is the number of bytes read from the primary document in parsing and
2207  <code>indirect</code> is the number of bytes added by expanding entities and reading of external DTD files, combined.
2208
2209  <p>For a call to <code>XML_SetBillionLaughsAttackProtectionMaximumAmplification</code> to succeed:</p>
2210  <ul>
2211    <li>parser <code>p</code> must be a non-<code>NULL</code> root parser (without any parent parsers) and</li>
2212    <li><code>maximumAmplificationFactor</code> must be non-<code>NaN</code> and greater than or equal to <code>1.0</code>.</li>
2213  </ul>
2214
2215  <p>
2216    <strong>Note:</strong>
2217    If you ever need to increase this value for non-attack payload,
2218    please <a href="https://github.com/libexpat/libexpat/issues">file a bug report</a>.
2219  </p>
2220
2221  <p>
2222    <strong>Note:</strong>
2223    Peak amplifications
2224    of factor 15,000 for the entire payload and
2225    of factor 30,000 in the middle of parsing
2226    have been observed with small benign files in practice.
2227
2228    So if you do reduce the maximum allowed amplification,
2229    please make sure that the activation threshold is still big enough
2230    to not end up with undesired false positives (i.e. benign files being rejected).
2231  </p>
2232</div>
2233
2234<h4 id="XML_SetBillionLaughsAttackProtectionActivationThreshold">XML_SetBillionLaughsAttackProtectionActivationThreshold</h4>
2235<pre class="fcndec">
2236/* Added in Expat 2.4.0. */
2237XML_Bool XMLCALL
2238XML_SetBillionLaughsAttackProtectionActivationThreshold(XML_Parser p,
2239                                                        unsigned long long activationThresholdBytes);
2240</pre>
2241<div class="fcndef">
2242  <p>
2243    Sets number of output bytes (including amplification from entity expansion and reading DTD files)
2244    needed to activate protection against
2245    <a href="https://en.wikipedia.org/wiki/Billion_laughs_attack">billion laughs attacks</a>
2246    (default: <code>8 MiB</code>)
2247    of parser <code>p</code> to <code>activationThresholdBytes</code>, and
2248    returns <code>XML_TRUE</code> upon success and <code>XML_FALSE</code> upon error.
2249  </p>
2250
2251  <p>For a call to <code>XML_SetBillionLaughsAttackProtectionActivationThreshold</code> to succeed:</p>
2252  <ul>
2253    <li>parser <code>p</code> must be a non-<code>NULL</code> root parser (without any parent parsers).</li>
2254  </ul>
2255
2256  <p>
2257    <strong>Note:</strong>
2258    If you ever need to increase this value for non-attack payload,
2259    please <a href="https://github.com/libexpat/libexpat/issues">file a bug report</a>.
2260  </p>
2261
2262  <p>
2263    <strong>Note:</strong>
2264    Activation thresholds below 4 MiB are known to break support for
2265    <a href="https://en.wikipedia.org/wiki/Darwin_Information_Typing_Architecture">DITA</a> 1.3 payload
2266    and are hence not recommended.
2267  </p>
2268</div>
2269
2270<h4 id="XML_SetReparseDeferralEnabled">XML_SetReparseDeferralEnabled</h4>
2271<pre class="fcndec">
2272/* Added in Expat 2.6.0. */
2273XML_Bool XMLCALL
2274XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled);
2275</pre>
2276<div class="fcndef">
2277  <p>
2278    Large tokens may require many parse calls before enough data is available for Expat to parse it in full.
2279    If Expat retried parsing the token on every parse call, parsing could take quadratic time.
2280    To avoid this, Expat only retries once a significant amount of new data is available.
2281    This function allows disabling this behavior.
2282  </p>
2283  <p>
2284    The <code>enabled</code> argument should be <code>XML_TRUE</code> or <code>XML_FALSE</code>.
2285  </p>
2286  <p>
2287    Returns <code>XML_TRUE</code> on success, and <code>XML_FALSE</code> on error.
2288  </p>
2289</div>
2290
2291<h3><a name="miscellaneous">Miscellaneous functions</a></h3>
2292
2293<p>The functions in this section either obtain state information from
2294the parser or can be used to dynamically set parser options.</p>
2295
2296<h4 id="XML_SetUserData">XML_SetUserData</h4>
2297<pre class="fcndec">
2298void XMLCALL
2299XML_SetUserData(XML_Parser p,
2300                void *userData);
2301</pre>
2302<div class="fcndef">
2303This sets the user data pointer that gets passed to handlers.  It
2304overwrites any previous value for this pointer. Note that the
2305application is responsible for freeing the memory associated with
2306<code>userData</code> when it is finished with the parser. So if you
2307call this when there's already a pointer there, and you haven't freed
2308the memory associated with it, then you've probably just leaked
2309memory.
2310</div>
2311
2312<h4 id="XML_GetUserData">XML_GetUserData</h4>
2313<pre class="fcndec">
2314void * XMLCALL
2315XML_GetUserData(XML_Parser p);
2316</pre>
2317<div class="fcndef">
2318This returns the user data pointer that gets passed to handlers.
2319It is actually implemented as a macro.
2320</div>
2321
2322<h4 id="XML_UseParserAsHandlerArg">XML_UseParserAsHandlerArg</h4>
2323<pre class="fcndec">
2324void XMLCALL
2325XML_UseParserAsHandlerArg(XML_Parser p);
2326</pre>
2327<div class="fcndef">
2328After this is called, handlers receive the parser in their
2329<code>userData</code> arguments.  The user data can still be obtained
2330using the <code><a href= "#XML_GetUserData"
2331>XML_GetUserData</a></code> function.
2332</div>
2333
2334<h4 id="XML_SetBase">XML_SetBase</h4>
2335<pre class="fcndec">
2336enum XML_Status XMLCALL
2337XML_SetBase(XML_Parser p,
2338            const XML_Char *base);
2339</pre>
2340<div class="fcndef">
2341Set the base to be used for resolving relative URIs in system
2342identifiers.  The return value is <code>XML_STATUS_ERROR</code> if
2343there's no memory to store base, otherwise it's
2344<code>XML_STATUS_OK</code>.
2345</div>
2346
2347<h4 id="XML_GetBase">XML_GetBase</h4>
2348<pre class="fcndec">
2349const XML_Char * XMLCALL
2350XML_GetBase(XML_Parser p);
2351</pre>
2352<div class="fcndef">
2353Return the base for resolving relative URIs.
2354</div>
2355
2356<h4 id="XML_GetSpecifiedAttributeCount">XML_GetSpecifiedAttributeCount</h4>
2357<pre class="fcndec">
2358int XMLCALL
2359XML_GetSpecifiedAttributeCount(XML_Parser p);
2360</pre>
2361<div class="fcndef">
2362When attributes are reported to the start handler in the atts vector,
2363attributes that were explicitly set in the element occur before any
2364attributes that receive their value from default information in an
2365ATTLIST declaration. This function returns the number of attributes
2366that were explicitly set times two, thus giving the offset in the
2367<code>atts</code> array passed to the start tag handler of the first
2368attribute set due to defaults. It supplies information for the last
2369call to a start handler. If called inside a start handler, then that
2370means the current call.
2371</div>
2372
2373<h4 id="XML_GetIdAttributeIndex">XML_GetIdAttributeIndex</h4>
2374<pre class="fcndec">
2375int XMLCALL
2376XML_GetIdAttributeIndex(XML_Parser p);
2377</pre>
2378<div class="fcndef">
2379Returns the index of the ID attribute passed in the atts array in the
2380last call to <code><a href= "#XML_StartElementHandler"
2381>XML_StartElementHandler</a></code>, or -1 if there is no ID
2382attribute. If called inside a start handler, then that means the
2383current call.
2384</div>
2385
2386<h4 id="XML_GetAttributeInfo">XML_GetAttributeInfo</h4>
2387<pre class="fcndec">
2388const XML_AttrInfo * XMLCALL
2389XML_GetAttributeInfo(XML_Parser parser);
2390</pre>
2391<pre class="signature">
2392typedef struct {
2393  XML_Index  nameStart;  /* Offset to beginning of the attribute name. */
2394  XML_Index  nameEnd;    /* Offset after the attribute name's last byte. */
2395  XML_Index  valueStart; /* Offset to beginning of the attribute value. */
2396  XML_Index  valueEnd;   /* Offset after the attribute value's last byte. */
2397} XML_AttrInfo;
2398</pre>
2399<div class="fcndef">
2400Returns an array of <code>XML_AttrInfo</code> structures for the
2401attribute/value pairs passed in the last call to the
2402<code>XML_StartElementHandler</code> that were specified
2403in the start-tag rather than defaulted. Each attribute/value pair counts
2404as 1; thus the number of entries in the array is
2405<code>XML_GetSpecifiedAttributeCount(parser) / 2</code>.
2406</div>
2407
2408<h4 id="XML_SetEncoding">XML_SetEncoding</h4>
2409<pre class="fcndec">
2410enum XML_Status XMLCALL
2411XML_SetEncoding(XML_Parser p,
2412                const XML_Char *encoding);
2413</pre>
2414<div class="fcndef">
2415Set the encoding to be used by the parser. It is equivalent to
2416passing a non-<code>NULL</code> encoding argument to the parser creation functions.
2417It must not be called after <code><a href= "#XML_Parse"
2418>XML_Parse</a></code> or <code><a href= "#XML_ParseBuffer"
2419>XML_ParseBuffer</a></code> have been called on the given parser.
2420Returns <code>XML_STATUS_OK</code> on success or
2421<code>XML_STATUS_ERROR</code> on error.
2422</div>
2423
2424<h4 id="XML_SetParamEntityParsing">XML_SetParamEntityParsing</h4>
2425<pre class="fcndec">
2426int XMLCALL
2427XML_SetParamEntityParsing(XML_Parser p,
2428                          enum XML_ParamEntityParsing code);
2429</pre>
2430<div class="fcndef">
2431This enables parsing of parameter entities, including the external
2432parameter entity that is the external DTD subset, according to
2433<code>code</code>.
2434The choices for <code>code</code> are:
2435<ul>
2436<li><code>XML_PARAM_ENTITY_PARSING_NEVER</code></li>
2437<li><code>XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE</code></li>
2438<li><code>XML_PARAM_ENTITY_PARSING_ALWAYS</code></li>
2439</ul>
2440<b>Note:</b> If <code>XML_SetParamEntityParsing</code> is called after
2441<code>XML_Parse</code> or <code>XML_ParseBuffer</code>, then it has
2442no effect and will always return 0.
2443</div>
2444
2445<h4 id="XML_SetHashSalt">XML_SetHashSalt</h4>
2446<pre class="fcndec">
2447int XMLCALL
2448XML_SetHashSalt(XML_Parser p,
2449                unsigned long hash_salt);
2450</pre>
2451<div class="fcndef">
2452Sets the hash salt to use for internal hash calculations.
2453Helps in preventing DoS attacks based on predicting hash
2454function behavior. In order to have an effect this must be called
2455before parsing has started. Returns 1 if successful, 0 when called
2456after <code>XML_Parse</code> or <code>XML_ParseBuffer</code>.
2457<p><b>Note:</b> This call is optional, as the parser will auto-generate
2458a new random salt value if no value has been set at the start of parsing.</p>
2459<p><b>Note:</b> One should not call <code>XML_SetHashSalt</code> with a
2460hash salt value of 0, as this value is used as sentinel value to indicate
2461that <code>XML_SetHashSalt</code> has <b>not</b> been called. Consequently
2462such a call will have no effect, even if it returns 1.</p>
2463</div>
2464
2465<h4 id="XML_UseForeignDTD">XML_UseForeignDTD</h4>
2466<pre class="fcndec">
2467enum XML_Error XMLCALL
2468XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);
2469</pre>
2470<div class="fcndef">
2471<p>This function allows an application to provide an external subset
2472for the document type declaration for documents which do not specify
2473an external subset of their own.  For documents which specify an
2474external subset in their DOCTYPE declaration, the application-provided
2475subset will be ignored.  If the document does not contain a DOCTYPE
2476declaration at all and <code>useDTD</code> is true, the
2477application-provided subset will be parsed, but the
2478<code>startDoctypeDeclHandler</code> and
2479<code>endDoctypeDeclHandler</code> functions, if set, will not be
2480called.  The setting of parameter entity parsing, controlled using
2481<code><a href= "#XML_SetParamEntityParsing"
2482>XML_SetParamEntityParsing</a></code>, will be honored.</p>
2483
2484<p>The application-provided external subset is read by calling the
2485external entity reference handler set via <code><a href=
2486"#XML_SetExternalEntityRefHandler"
2487>XML_SetExternalEntityRefHandler</a></code> with both
2488<code>publicId</code> and <code>systemId</code> set to <code>NULL</code>.</p>
2489
2490<p>If this function is called after parsing has begun, it returns
2491<code>XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING</code> and ignores
2492<code>useDTD</code>.  If called when Expat has been compiled without
2493DTD support, it returns
2494<code>XML_ERROR_FEATURE_REQUIRES_XML_DTD</code>.  Otherwise, it
2495returns <code>XML_ERROR_NONE</code>.</p>
2496
2497<p><b>Note:</b> For the purpose of checking WFC: Entity Declared, passing
2498<code>useDTD == XML_TRUE</code> will make the parser behave as if
2499the document had a DTD with an external subset. This holds true even if
2500the external entity reference handler returns without action.</p>
2501</div>
2502
2503<h4 id="XML_SetReturnNSTriplet">XML_SetReturnNSTriplet</h4>
2504<pre class="fcndec">
2505void XMLCALL
2506XML_SetReturnNSTriplet(XML_Parser parser,
2507                       int        do_nst);
2508</pre>
2509<div class="fcndef">
2510<p>
2511This function only has an effect when using a parser created with
2512<code><a href= "#XML_ParserCreateNS" >XML_ParserCreateNS</a></code>,
2513i.e. when namespace processing is in effect. The <code>do_nst</code>
2514sets whether or not prefixes are returned with names qualified with a
2515namespace prefix. If this function is called with <code>do_nst</code>
2516non-zero, then afterwards namespace qualified names (that is qualified
2517with a prefix as opposed to belonging to a default namespace) are
2518returned as a triplet with the three parts separated by the namespace
2519separator specified when the parser was created.  The order of
2520returned parts is URI, local name, and prefix.</p> <p>If
2521<code>do_nst</code> is zero, then namespaces are reported in the
2522default manner, URI then local_name separated by the namespace
2523separator.</p>
2524</div>
2525
2526<h4 id="XML_DefaultCurrent">XML_DefaultCurrent</h4>
2527<pre class="fcndec">
2528void XMLCALL
2529XML_DefaultCurrent(XML_Parser parser);
2530</pre>
2531<div class="fcndef">
2532This can be called within a handler for a start element, end element,
2533processing instruction or character data.  It causes the corresponding
2534markup to be passed to the default handler set by <code><a
2535href="#XML_SetDefaultHandler" >XML_SetDefaultHandler</a></code> or
2536<code><a href="#XML_SetDefaultHandlerExpand"
2537>XML_SetDefaultHandlerExpand</a></code>.  It does nothing if there is
2538not a default handler.
2539</div>
2540
2541<h4 id="XML_ExpatVersion">XML_ExpatVersion</h4>
2542<pre class="fcndec">
2543XML_LChar * XMLCALL
2544XML_ExpatVersion();
2545</pre>
2546<div class="fcndef">
2547Return the library version as a string (e.g. <code>"expat_1.95.1"</code>).
2548</div>
2549
2550<h4 id="XML_ExpatVersionInfo">XML_ExpatVersionInfo</h4>
2551<pre class="fcndec">
2552struct XML_Expat_Version XMLCALL
2553XML_ExpatVersionInfo();
2554</pre>
2555<pre class="signature">
2556typedef struct {
2557  int major;
2558  int minor;
2559  int micro;
2560} XML_Expat_Version;
2561</pre>
2562<div class="fcndef">
2563Return the library version information as a structure.
2564Some macros are also defined that support compile-time tests of the
2565library version:
2566<ul>
2567<li><code>XML_MAJOR_VERSION</code></li>
2568<li><code>XML_MINOR_VERSION</code></li>
2569<li><code>XML_MICRO_VERSION</code></li>
2570</ul>
2571Testing these constants is currently the best way to determine if
2572particular parts of the Expat API are available.
2573</div>
2574
2575<h4 id="XML_GetFeatureList">XML_GetFeatureList</h4>
2576<pre class="fcndec">
2577const XML_Feature * XMLCALL
2578XML_GetFeatureList();
2579</pre>
2580<pre class="signature">
2581enum XML_FeatureEnum {
2582  XML_FEATURE_END = 0,
2583  XML_FEATURE_UNICODE,
2584  XML_FEATURE_UNICODE_WCHAR_T,
2585  XML_FEATURE_DTD,
2586  XML_FEATURE_CONTEXT_BYTES,
2587  XML_FEATURE_MIN_SIZE,
2588  XML_FEATURE_SIZEOF_XML_CHAR,
2589  XML_FEATURE_SIZEOF_XML_LCHAR,
2590  XML_FEATURE_NS,
2591  XML_FEATURE_LARGE_SIZE
2592};
2593
2594typedef struct {
2595  enum XML_FeatureEnum  feature;
2596  XML_LChar            *name;
2597  long int              value;
2598} XML_Feature;
2599</pre>
2600<div class="fcndef">
2601<p>Returns a list of "feature" records, providing details on how
2602Expat was configured at compile time.  Most applications should not
2603need to worry about this, but this information is otherwise not
2604available from Expat.  This function allows code that does need to
2605check these features to do so at runtime.</p>
2606
2607<p>The return value is an array of <code>XML_Feature</code>,
2608terminated by a record with a <code>feature</code> of
2609<code>XML_FEATURE_END</code> and <code>name</code> of <code>NULL</code>,
2610identifying the feature-test macros Expat was compiled with.  Since an
2611application that requires this kind of information needs to determine
2612the type of character the <code>name</code> points to, records for the
2613<code>XML_FEATURE_SIZEOF_XML_CHAR</code> and
2614<code>XML_FEATURE_SIZEOF_XML_LCHAR</code> will be located at the
2615beginning of the list, followed by <code>XML_FEATURE_UNICODE</code>
2616and <code>XML_FEATURE_UNICODE_WCHAR_T</code>, if they are present at
2617all.</p>
2618
2619<p>Some features have an associated value.  If there isn't an
2620associated value, the <code>value</code> field is set to 0.  At this
2621time, the following features have been defined to have values:</p>
2622
2623<dl>
2624  <dt><code>XML_FEATURE_SIZEOF_XML_CHAR</code></dt>
2625  <dd>The number of bytes occupied by one <code>XML_Char</code>
2626  character.</dd>
2627  <dt><code>XML_FEATURE_SIZEOF_XML_LCHAR</code></dt>
2628  <dd>The number of bytes occupied by one <code>XML_LChar</code>
2629  character.</dd>
2630  <dt><code>XML_FEATURE_CONTEXT_BYTES</code></dt>
2631  <dd>The maximum number of characters of context which can be
2632  reported by <code><a href= "#XML_GetInputContext"
2633  >XML_GetInputContext</a></code>.</dd>
2634</dl>
2635</div>
2636
2637<h4 id="XML_FreeContentModel">XML_FreeContentModel</h4>
2638<pre class="fcndec">
2639void XMLCALL
2640XML_FreeContentModel(XML_Parser parser, XML_Content *model);
2641</pre>
2642<div class="fcndef">
2643Function to deallocate the <code>model</code> argument passed to the
2644<code>XML_ElementDeclHandler</code> callback set using <code><a
2645href="#XML_SetElementDeclHandler" >XML_ElementDeclHandler</a></code>.
2646This function should not be used for any other purpose.
2647</div>
2648
2649<p>The following functions allow external code to share the memory
2650allocator an <code>XML_Parser</code> has been configured to use.  This
2651is especially useful for third-party libraries that interact with a
2652parser object created by application code, or heavily layered
2653applications.  This can be essential when using dynamically loaded
2654libraries which use different C standard libraries (this can happen on
2655Windows, at least).</p>
2656
2657<h4 id="XML_MemMalloc">XML_MemMalloc</h4>
2658<pre class="fcndec">
2659void * XMLCALL
2660XML_MemMalloc(XML_Parser parser, size_t size);
2661</pre>
2662<div class="fcndef">
2663Allocate <code>size</code> bytes of memory using the allocator the
2664<code>parser</code> object has been configured to use.  Returns a
2665pointer to the memory or <code>NULL</code> on failure.  Memory allocated in this
2666way must be freed using <code><a href="#XML_MemFree"
2667>XML_MemFree</a></code>.
2668</div>
2669
2670<h4 id="XML_MemRealloc">XML_MemRealloc</h4>
2671<pre class="fcndec">
2672void * XMLCALL
2673XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);
2674</pre>
2675<div class="fcndef">
2676Allocate <code>size</code> bytes of memory using the allocator the
2677<code>parser</code> object has been configured to use.
2678<code>ptr</code> must point to a block of memory allocated by <code><a
2679href="#XML_MemMalloc" >XML_MemMalloc</a></code> or
2680<code>XML_MemRealloc</code>, or be <code>NULL</code>.  This function tries to
2681expand the block pointed to by <code>ptr</code> if possible.  Returns
2682a pointer to the memory or <code>NULL</code> on failure.  On success, the original
2683block has either been expanded or freed.  On failure, the original
2684block has not been freed; the caller is responsible for freeing the
2685original block.  Memory allocated in this way must be freed using
2686<code><a href="#XML_MemFree"
2687>XML_MemFree</a></code>.
2688</div>
2689
2690<h4 id="XML_MemFree">XML_MemFree</h4>
2691<pre class="fcndec">
2692void XMLCALL
2693XML_MemFree(XML_Parser parser, void *ptr);
2694</pre>
2695<div class="fcndef">
2696Free a block of memory pointed to by <code>ptr</code>.  The block must
2697have been allocated by <code><a href="#XML_MemMalloc"
2698>XML_MemMalloc</a></code> or <code>XML_MemRealloc</code>, or be <code>NULL</code>.
2699</div>
2700
2701<hr />
2702
2703  <div class="footer">
2704    Found a bug in the documentation?
2705    <a href="https://github.com/libexpat/libexpat/issues">Please file a bug report.</a>
2706  </div>
2707
2708</div>
2709</body>
2710</html>
2711