xref: /freebsd/contrib/expat/doc/reference.html (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
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-2024 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.6.4</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_SUSPENDED</code></dt>
1271  <dd>when suspending an already suspended parser.</dd>
1272  <dt><code>XML_ERROR_FINISHED</code></dt>
1273  <dd>when the parser has already finished.</dd>
1274  <dt><code>XML_ERROR_SUSPEND_PE</code></dt>
1275  <dd>when suspending while parsing an external PE.</dd>
1276</dl>
1277
1278<p>Since the stop/resume feature requires application support in the
1279outer parsing loop, it is an error to call this function for a parser
1280not being handled appropriately; see <a href= "#stop-resume"
1281>Temporarily Stopping Parsing</a> for more information.</p>
1282
1283<p>When <code>resumable</code> is <code>XML_TRUE</code> then parsing
1284is <em>suspended</em>, that is, <code><a href= "#XML_Parse"
1285>XML_Parse</a></code> and <code><a href= "#XML_ParseBuffer"
1286>XML_ParseBuffer</a></code> return <code>XML_STATUS_SUSPENDED</code>.
1287Otherwise, parsing is <em>aborted</em>, that is, <code><a href=
1288"#XML_Parse" >XML_Parse</a></code> and <code><a href=
1289"#XML_ParseBuffer" >XML_ParseBuffer</a></code> return
1290<code>XML_STATUS_ERROR</code> with error code
1291<code>XML_ERROR_ABORTED</code>.</p>
1292
1293<p><strong>Note:</strong>
1294This will be applied to the current parser instance only, that is, if
1295there is a parent parser then it will continue parsing when the
1296external entity reference handler returns.  It is up to the
1297implementation of that handler to call <code><a href=
1298"#XML_StopParser" >XML_StopParser</a></code> on the parent parser
1299(recursively), if one wants to stop parsing altogether.</p>
1300
1301<p>When suspended, parsing can be resumed by calling <code><a href=
1302"#XML_ResumeParser" >XML_ResumeParser</a></code>.</p>
1303
1304<p>New in Expat 1.95.8.</p>
1305</div>
1306
1307<h4 id="XML_ResumeParser">XML_ResumeParser</h4>
1308<pre class="fcndec">
1309enum XML_Status XMLCALL
1310XML_ResumeParser(XML_Parser p);
1311</pre>
1312<div class="fcndef">
1313<p>Resumes parsing after it has been suspended with <code><a href=
1314"#XML_StopParser" >XML_StopParser</a></code>.  Must not be called from
1315within a handler call-back.  Returns same status codes as <code><a
1316href= "#XML_Parse">XML_Parse</a></code> or <code><a href=
1317"#XML_ParseBuffer" >XML_ParseBuffer</a></code>.  An additional error
1318code, <code>XML_ERROR_NOT_SUSPENDED</code>, will be returned if the
1319parser was not currently suspended.</p>
1320
1321<p><strong>Note:</strong>
1322This must be called on the most deeply nested child parser instance
1323first, and on its parent parser only after the child parser has
1324finished, to be applied recursively until the document entity's parser
1325is restarted.  That is, the parent parser will not resume by itself
1326and it is up to the application to call <code><a href=
1327"#XML_ResumeParser" >XML_ResumeParser</a></code> on it at the
1328appropriate moment.</p>
1329
1330<p>New in Expat 1.95.8.</p>
1331</div>
1332
1333<h4 id="XML_GetParsingStatus">XML_GetParsingStatus</h4>
1334<pre class="fcndec">
1335void XMLCALL
1336XML_GetParsingStatus(XML_Parser p,
1337                     XML_ParsingStatus *status);
1338</pre>
1339<pre class="signature">
1340enum XML_Parsing {
1341  XML_INITIALIZED,
1342  XML_PARSING,
1343  XML_FINISHED,
1344  XML_SUSPENDED
1345};
1346
1347typedef struct {
1348  enum XML_Parsing parsing;
1349  XML_Bool finalBuffer;
1350} XML_ParsingStatus;
1351</pre>
1352<div class="fcndef">
1353<p>Returns status of parser with respect to being initialized,
1354parsing, finished, or suspended, and whether the final buffer is being
1355processed.  The <code>status</code> parameter <em>must not</em> be
1356<code>NULL</code>.</p>
1357
1358<p>New in Expat 1.95.8.</p>
1359</div>
1360
1361
1362<h3><a name="setting">Handler Setting</a></h3>
1363
1364<p>Although handlers are typically set prior to parsing and left alone, an
1365application may choose to set or change the handler for a parsing event
1366while the parse is in progress. For instance, your application may choose
1367to ignore all text not descended from a <code>para</code> element. One
1368way it could do this is to set the character handler when a para start tag
1369is seen, and unset it for the corresponding end tag.</p>
1370
1371<p>A handler may be <em>unset</em> by providing a <code>NULL</code> pointer to the
1372appropriate handler setter. None of the handler setting functions have
1373a return value.</p>
1374
1375<p>Your handlers will be receiving strings in arrays of type
1376<code>XML_Char</code>. This type is conditionally defined in expat.h as
1377either <code>char</code>, <code>wchar_t</code> or <code>unsigned short</code>.
1378The former implies UTF-8 encoding, the latter two imply UTF-16 encoding.
1379Note that you'll receive them in this form independent of the original
1380encoding of the document.</p>
1381
1382<div class="handler">
1383<h4 id="XML_SetStartElementHandler">XML_SetStartElementHandler</h4>
1384<pre class="setter">
1385void XMLCALL
1386XML_SetStartElementHandler(XML_Parser p,
1387                           XML_StartElementHandler start);
1388</pre>
1389<pre class="signature">
1390typedef void
1391(XMLCALL *XML_StartElementHandler)(void *userData,
1392                                   const XML_Char *name,
1393                                   const XML_Char **atts);
1394</pre>
1395<p>Set handler for start (and empty) tags. Attributes are passed to the start
1396handler as a pointer to a vector of char pointers. Each attribute seen in
1397a start (or empty) tag occupies 2 consecutive places in this vector: the
1398attribute name followed by the attribute value. These pairs are terminated
1399by a <code>NULL</code> pointer.</p>
1400<p>Note that an empty tag generates a call to both start and end handlers
1401(in that order).</p>
1402</div>
1403
1404<div class="handler">
1405<h4 id="XML_SetEndElementHandler">XML_SetEndElementHandler</h4>
1406<pre class="setter">
1407void XMLCALL
1408XML_SetEndElementHandler(XML_Parser p,
1409                         XML_EndElementHandler);
1410</pre>
1411<pre class="signature">
1412typedef void
1413(XMLCALL *XML_EndElementHandler)(void *userData,
1414                                 const XML_Char *name);
1415</pre>
1416<p>Set handler for end (and empty) tags. As noted above, an empty tag
1417generates a call to both start and end handlers.</p>
1418</div>
1419
1420<div class="handler">
1421<h4 id="XML_SetElementHandler">XML_SetElementHandler</h4>
1422<pre class="setter">
1423void XMLCALL
1424XML_SetElementHandler(XML_Parser p,
1425                      XML_StartElementHandler start,
1426                      XML_EndElementHandler end);
1427</pre>
1428<p>Set handlers for start and end tags with one call.</p>
1429</div>
1430
1431<div class="handler">
1432<h4 id="XML_SetCharacterDataHandler">XML_SetCharacterDataHandler</h4>
1433<pre class="setter">
1434void XMLCALL
1435XML_SetCharacterDataHandler(XML_Parser p,
1436                            XML_CharacterDataHandler charhndl)
1437</pre>
1438<pre class="signature">
1439typedef void
1440(XMLCALL *XML_CharacterDataHandler)(void *userData,
1441                                    const XML_Char *s,
1442                                    int len);
1443</pre>
1444<p>Set a text handler. The string your handler receives
1445is <em>NOT null-terminated</em>. You have to use the length argument
1446to deal with the end of the string. A single block of contiguous text
1447free of markup may still result in a sequence of calls to this handler.
1448In other words, if you're searching for a pattern in the text, it may
1449be split across calls to this handler. Note: Setting this handler to <code>NULL</code>
1450may <em>NOT immediately</em> terminate call-backs if the parser is currently
1451processing such a single block of contiguous markup-free text, as the parser
1452will continue calling back until the end of the block is reached.</p>
1453</div>
1454
1455<div class="handler">
1456<h4 id="XML_SetProcessingInstructionHandler">XML_SetProcessingInstructionHandler</h4>
1457<pre class="setter">
1458void XMLCALL
1459XML_SetProcessingInstructionHandler(XML_Parser p,
1460                                    XML_ProcessingInstructionHandler proc)
1461</pre>
1462<pre class="signature">
1463typedef void
1464(XMLCALL *XML_ProcessingInstructionHandler)(void *userData,
1465                                            const XML_Char *target,
1466                                            const XML_Char *data);
1467
1468</pre>
1469<p>Set a handler for processing instructions. The target is the first word
1470in the processing instruction. The data is the rest of the characters in
1471it after skipping all whitespace after the initial word.</p>
1472</div>
1473
1474<div class="handler">
1475<h4 id="XML_SetCommentHandler">XML_SetCommentHandler</h4>
1476<pre class="setter">
1477void XMLCALL
1478XML_SetCommentHandler(XML_Parser p,
1479                      XML_CommentHandler cmnt)
1480</pre>
1481<pre class="signature">
1482typedef void
1483(XMLCALL *XML_CommentHandler)(void *userData,
1484                              const XML_Char *data);
1485</pre>
1486<p>Set a handler for comments. The data is all text inside the comment
1487delimiters.</p>
1488</div>
1489
1490<div class="handler">
1491<h4 id="XML_SetStartCdataSectionHandler">XML_SetStartCdataSectionHandler</h4>
1492<pre class="setter">
1493void XMLCALL
1494XML_SetStartCdataSectionHandler(XML_Parser p,
1495                                XML_StartCdataSectionHandler start);
1496</pre>
1497<pre class="signature">
1498typedef void
1499(XMLCALL *XML_StartCdataSectionHandler)(void *userData);
1500</pre>
1501<p>Set a handler that gets called at the beginning of a CDATA section.</p>
1502</div>
1503
1504<div class="handler">
1505<h4 id="XML_SetEndCdataSectionHandler">XML_SetEndCdataSectionHandler</h4>
1506<pre class="setter">
1507void XMLCALL
1508XML_SetEndCdataSectionHandler(XML_Parser p,
1509                              XML_EndCdataSectionHandler end);
1510</pre>
1511<pre class="signature">
1512typedef void
1513(XMLCALL *XML_EndCdataSectionHandler)(void *userData);
1514</pre>
1515<p>Set a handler that gets called at the end of a CDATA section.</p>
1516</div>
1517
1518<div class="handler">
1519<h4 id="XML_SetCdataSectionHandler">XML_SetCdataSectionHandler</h4>
1520<pre class="setter">
1521void XMLCALL
1522XML_SetCdataSectionHandler(XML_Parser p,
1523                           XML_StartCdataSectionHandler start,
1524                           XML_EndCdataSectionHandler end)
1525</pre>
1526<p>Sets both CDATA section handlers with one call.</p>
1527</div>
1528
1529<div class="handler">
1530<h4 id="XML_SetDefaultHandler">XML_SetDefaultHandler</h4>
1531<pre class="setter">
1532void XMLCALL
1533XML_SetDefaultHandler(XML_Parser p,
1534                      XML_DefaultHandler hndl)
1535</pre>
1536<pre class="signature">
1537typedef void
1538(XMLCALL *XML_DefaultHandler)(void *userData,
1539                              const XML_Char *s,
1540                              int len);
1541</pre>
1542
1543<p>Sets a handler for any characters in the document which wouldn't
1544otherwise be handled. This includes both data for which no handlers
1545can be set (like some kinds of DTD declarations) and data which could
1546be reported but which currently has no handler set.  The characters
1547are passed exactly as they were present in the XML document except
1548that they will be encoded in UTF-8 or UTF-16. Line boundaries are not
1549normalized. Note that a byte order mark character is not passed to the
1550default handler. There are no guarantees about how characters are
1551divided between calls to the default handler: for example, a comment
1552might be split between multiple calls.  Setting the handler with
1553this call has the side effect of turning off expansion of references
1554to internally defined general entities. Instead these references are
1555passed to the default handler.</p>
1556
1557<p>See also <code><a
1558href="#XML_DefaultCurrent">XML_DefaultCurrent</a></code>.</p>
1559</div>
1560
1561<div class="handler">
1562<h4 id="XML_SetDefaultHandlerExpand">XML_SetDefaultHandlerExpand</h4>
1563<pre class="setter">
1564void XMLCALL
1565XML_SetDefaultHandlerExpand(XML_Parser p,
1566                            XML_DefaultHandler hndl)
1567</pre>
1568<pre class="signature">
1569typedef void
1570(XMLCALL *XML_DefaultHandler)(void *userData,
1571                              const XML_Char *s,
1572                              int len);
1573</pre>
1574<p>This sets a default handler, but doesn't inhibit the expansion of
1575internal entity references.  The entity reference will not be passed
1576to the default handler.</p>
1577
1578<p>See also <code><a
1579href="#XML_DefaultCurrent">XML_DefaultCurrent</a></code>.</p>
1580</div>
1581
1582<div class="handler">
1583<h4 id="XML_SetExternalEntityRefHandler">XML_SetExternalEntityRefHandler</h4>
1584<pre class="setter">
1585void XMLCALL
1586XML_SetExternalEntityRefHandler(XML_Parser p,
1587                                XML_ExternalEntityRefHandler hndl)
1588</pre>
1589<pre class="signature">
1590typedef int
1591(XMLCALL *XML_ExternalEntityRefHandler)(XML_Parser p,
1592                                        const XML_Char *context,
1593                                        const XML_Char *base,
1594                                        const XML_Char *systemId,
1595                                        const XML_Char *publicId);
1596</pre>
1597<p>Set an external entity reference handler. This handler is also
1598called for processing an external DTD subset if parameter entity parsing
1599is in effect. (See <a href="#XML_SetParamEntityParsing">
1600<code>XML_SetParamEntityParsing</code></a>.)</p>
1601
1602<p>The <code>context</code> parameter specifies the parsing context in
1603the format expected by the <code>context</code> argument to <code><a
1604href="#XML_ExternalEntityParserCreate"
1605>XML_ExternalEntityParserCreate</a></code>.  <code>code</code> is
1606valid only until the handler returns, so if the referenced entity is
1607to be parsed later, it must be copied.  <code>context</code> is <code>NULL</code>
1608only when the entity is a parameter entity, which is how one can
1609differentiate between general and parameter entities.</p>
1610
1611<p>The <code>base</code> parameter is the base to use for relative
1612system identifiers.  It is set by <code><a
1613href="#XML_SetBase">XML_SetBase</a></code> and may be <code>NULL</code>. The
1614<code>publicId</code> parameter is the public id given in the entity
1615declaration and may be <code>NULL</code>.  <code>systemId</code> is the system
1616identifier specified in the entity declaration and is never <code>NULL</code>.</p>
1617
1618<p>There are a couple of ways in which this handler differs from
1619others.  First, this handler returns a status indicator (an
1620integer). <code>XML_STATUS_OK</code> should be returned for successful
1621handling of the external entity reference.  Returning
1622<code>XML_STATUS_ERROR</code> indicates failure, and causes the
1623calling parser to return an
1624<code>XML_ERROR_EXTERNAL_ENTITY_HANDLING</code> error.</p>
1625
1626<p>Second, instead of having the user data as its first argument, it
1627receives the parser that encountered the entity reference. This, along
1628with the context parameter, may be used as arguments to a call to
1629<code><a href= "#XML_ExternalEntityParserCreate"
1630>XML_ExternalEntityParserCreate</a></code>.  Using the returned
1631parser, the body of the external entity can be recursively parsed.</p>
1632
1633<p>Since this handler may be called recursively, it should not be saving
1634information into global or static variables.</p>
1635</div>
1636
1637<h4 id="XML_SetExternalEntityRefHandlerArg">XML_SetExternalEntityRefHandlerArg</h4>
1638<pre class="fcndec">
1639void XMLCALL
1640XML_SetExternalEntityRefHandlerArg(XML_Parser p,
1641                                   void *arg)
1642</pre>
1643<div class="fcndef">
1644<p>Set the argument passed to the ExternalEntityRefHandler.  If
1645<code>arg</code> is not <code>NULL</code>, it is the new value passed to the
1646handler set using <code><a href="#XML_SetExternalEntityRefHandler"
1647>XML_SetExternalEntityRefHandler</a></code>; if <code>arg</code> is
1648<code>NULL</code>, the argument passed to the handler function will be the parser
1649object itself.</p>
1650
1651<p><strong>Note:</strong>
1652The type of <code>arg</code> and the type of the first argument to the
1653ExternalEntityRefHandler do not match.  This function takes a
1654<code>void *</code> to be passed to the handler, while the handler
1655accepts an <code>XML_Parser</code>.  This is a historical accident,
1656but will not be corrected before Expat 2.0 (at the earliest) to avoid
1657causing compiler warnings for code that's known to work with this
1658API.  It is the responsibility of the application code to know the
1659actual type of the argument passed to the handler and to manage it
1660properly.</p>
1661</div>
1662
1663<div class="handler">
1664<h4 id="XML_SetSkippedEntityHandler">XML_SetSkippedEntityHandler</h4>
1665<pre class="setter">
1666void XMLCALL
1667XML_SetSkippedEntityHandler(XML_Parser p,
1668                            XML_SkippedEntityHandler handler)
1669</pre>
1670<pre class="signature">
1671typedef void
1672(XMLCALL *XML_SkippedEntityHandler)(void *userData,
1673                                    const XML_Char *entityName,
1674                                    int is_parameter_entity);
1675</pre>
1676<p>Set a skipped entity handler. This is called in two situations:</p>
1677<ol>
1678   <li>An entity reference is encountered for which no declaration
1679       has been read <em>and</em> this is not an error.</li>
1680   <li>An internal entity reference is read, but not expanded, because
1681       <a href="#XML_SetDefaultHandler"><code>XML_SetDefaultHandler</code></a>
1682	   has been called.</li>
1683</ol>
1684<p>The <code>is_parameter_entity</code> argument will be non-zero for
1685a parameter entity and zero for a general entity.</p> <p>Note: Skipped
1686parameter entities in declarations and skipped general entities in
1687attribute values cannot be reported, because the event would be out of
1688sync with the reporting of the declarations or attribute values</p>
1689</div>
1690
1691<div class="handler">
1692<h4 id="XML_SetUnknownEncodingHandler">XML_SetUnknownEncodingHandler</h4>
1693<pre class="setter">
1694void XMLCALL
1695XML_SetUnknownEncodingHandler(XML_Parser p,
1696                              XML_UnknownEncodingHandler enchandler,
1697			      void *encodingHandlerData)
1698</pre>
1699<pre class="signature">
1700typedef int
1701(XMLCALL *XML_UnknownEncodingHandler)(void *encodingHandlerData,
1702                                      const XML_Char *name,
1703                                      XML_Encoding *info);
1704
1705typedef struct {
1706  int map[256];
1707  void *data;
1708  int (XMLCALL *convert)(void *data, const char *s);
1709  void (XMLCALL *release)(void *data);
1710} XML_Encoding;
1711</pre>
1712<p>Set a handler to deal with encodings other than the <a
1713href="#builtin_encodings">built in set</a>. This should be done before
1714<code><a href= "#XML_Parse" >XML_Parse</a></code> or <code><a href=
1715"#XML_ParseBuffer" >XML_ParseBuffer</a></code> have been called on the
1716given parser.</p> <p>If the handler knows how to deal with an encoding
1717with the given name, it should fill in the <code>info</code> data
1718structure and return <code>XML_STATUS_OK</code>. Otherwise it
1719should return <code>XML_STATUS_ERROR</code>. The handler will be called
1720at most once per parsed (external) entity. The optional application
1721data pointer <code>encodingHandlerData</code> will be passed back to
1722the handler.</p>
1723
1724<p>The map array contains information for every possible leading
1725byte in a byte sequence. If the corresponding value is &gt;= 0, then it's
1726a single byte sequence and the byte encodes that Unicode value. If the
1727value is -1, then that byte is invalid as the initial byte in a sequence.
1728If the value is -n, where n is an integer &gt; 1, then n is the number of
1729bytes in the sequence and the actual conversion is accomplished by a
1730call to the function pointed at by convert. This function may return -1
1731if the sequence itself is invalid. The convert pointer may be <code>NULL</code> if
1732there are only single byte codes. The data parameter passed to the convert
1733function is the data pointer from <code>XML_Encoding</code>. The
1734string s is <em>NOT</em> null-terminated and points at the sequence of
1735bytes to be converted.</p>
1736
1737<p>The function pointed at by <code>release</code> is called by the
1738parser when it is finished with the encoding. It may be <code>NULL</code>.</p>
1739</div>
1740
1741<div class="handler">
1742<h4 id="XML_SetStartNamespaceDeclHandler">XML_SetStartNamespaceDeclHandler</h4>
1743<pre class="setter">
1744void XMLCALL
1745XML_SetStartNamespaceDeclHandler(XML_Parser p,
1746			         XML_StartNamespaceDeclHandler start);
1747</pre>
1748<pre class="signature">
1749typedef void
1750(XMLCALL *XML_StartNamespaceDeclHandler)(void *userData,
1751                                         const XML_Char *prefix,
1752                                         const XML_Char *uri);
1753</pre>
1754<p>Set a handler to be called when a namespace is declared. Namespace
1755declarations occur inside start tags. But the namespace declaration start
1756handler is called before the start tag handler for each namespace declared
1757in that start tag.</p>
1758</div>
1759
1760<div class="handler">
1761<h4 id="XML_SetEndNamespaceDeclHandler">XML_SetEndNamespaceDeclHandler</h4>
1762<pre class="setter">
1763void XMLCALL
1764XML_SetEndNamespaceDeclHandler(XML_Parser p,
1765			       XML_EndNamespaceDeclHandler end);
1766</pre>
1767<pre class="signature">
1768typedef void
1769(XMLCALL *XML_EndNamespaceDeclHandler)(void *userData,
1770                                       const XML_Char *prefix);
1771</pre>
1772<p>Set a handler to be called when leaving the scope of a namespace
1773declaration. This will be called, for each namespace declaration,
1774after the handler for the end tag of the element in which the
1775namespace was declared.</p>
1776</div>
1777
1778<div class="handler">
1779<h4 id="XML_SetNamespaceDeclHandler">XML_SetNamespaceDeclHandler</h4>
1780<pre class="setter">
1781void XMLCALL
1782XML_SetNamespaceDeclHandler(XML_Parser p,
1783                            XML_StartNamespaceDeclHandler start,
1784                            XML_EndNamespaceDeclHandler end)
1785</pre>
1786<p>Sets both namespace declaration handlers with a single call.</p>
1787</div>
1788
1789<div class="handler">
1790<h4 id="XML_SetXmlDeclHandler">XML_SetXmlDeclHandler</h4>
1791<pre class="setter">
1792void XMLCALL
1793XML_SetXmlDeclHandler(XML_Parser p,
1794		      XML_XmlDeclHandler xmldecl);
1795</pre>
1796<pre class="signature">
1797typedef void
1798(XMLCALL *XML_XmlDeclHandler)(void            *userData,
1799                              const XML_Char  *version,
1800                              const XML_Char  *encoding,
1801                              int             standalone);
1802</pre>
1803<p>Sets a handler that is called for XML declarations and also for
1804text declarations discovered in external entities. The way to
1805distinguish is that the <code>version</code> parameter will be <code>NULL</code>
1806for text declarations. The <code>encoding</code> parameter may be <code>NULL</code>
1807for an XML declaration. The <code>standalone</code> argument will
1808contain -1, 0, or 1 indicating respectively that there was no
1809standalone parameter in the declaration, that it was given as no, or
1810that it was given as yes.</p>
1811</div>
1812
1813<div class="handler">
1814<h4 id="XML_SetStartDoctypeDeclHandler">XML_SetStartDoctypeDeclHandler</h4>
1815<pre class="setter">
1816void XMLCALL
1817XML_SetStartDoctypeDeclHandler(XML_Parser p,
1818			       XML_StartDoctypeDeclHandler start);
1819</pre>
1820<pre class="signature">
1821typedef void
1822(XMLCALL *XML_StartDoctypeDeclHandler)(void           *userData,
1823                                       const XML_Char *doctypeName,
1824                                       const XML_Char *sysid,
1825                                       const XML_Char *pubid,
1826                                       int            has_internal_subset);
1827</pre>
1828<p>Set a handler that is called at the start of a DOCTYPE declaration,
1829before any external or internal subset is parsed. Both <code>sysid</code>
1830and <code>pubid</code> may be <code>NULL</code>. The <code>has_internal_subset</code>
1831will be non-zero if the DOCTYPE declaration has an internal subset.</p>
1832</div>
1833
1834<div class="handler">
1835<h4 id="XML_SetEndDoctypeDeclHandler">XML_SetEndDoctypeDeclHandler</h4>
1836<pre class="setter">
1837void XMLCALL
1838XML_SetEndDoctypeDeclHandler(XML_Parser p,
1839			     XML_EndDoctypeDeclHandler end);
1840</pre>
1841<pre class="signature">
1842typedef void
1843(XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
1844</pre>
1845<p>Set a handler that is called at the end of a DOCTYPE declaration,
1846after parsing any external subset.</p>
1847</div>
1848
1849<div class="handler">
1850<h4 id="XML_SetDoctypeDeclHandler">XML_SetDoctypeDeclHandler</h4>
1851<pre class="setter">
1852void XMLCALL
1853XML_SetDoctypeDeclHandler(XML_Parser p,
1854			  XML_StartDoctypeDeclHandler start,
1855			  XML_EndDoctypeDeclHandler end);
1856</pre>
1857<p>Set both doctype handlers with one call.</p>
1858</div>
1859
1860<div class="handler">
1861<h4 id="XML_SetElementDeclHandler">XML_SetElementDeclHandler</h4>
1862<pre class="setter">
1863void XMLCALL
1864XML_SetElementDeclHandler(XML_Parser p,
1865			  XML_ElementDeclHandler eldecl);
1866</pre>
1867<pre class="signature">
1868typedef void
1869(XMLCALL *XML_ElementDeclHandler)(void *userData,
1870                                  const XML_Char *name,
1871                                  XML_Content *model);
1872</pre>
1873<pre class="signature">
1874enum XML_Content_Type {
1875  XML_CTYPE_EMPTY = 1,
1876  XML_CTYPE_ANY,
1877  XML_CTYPE_MIXED,
1878  XML_CTYPE_NAME,
1879  XML_CTYPE_CHOICE,
1880  XML_CTYPE_SEQ
1881};
1882
1883enum XML_Content_Quant {
1884  XML_CQUANT_NONE,
1885  XML_CQUANT_OPT,
1886  XML_CQUANT_REP,
1887  XML_CQUANT_PLUS
1888};
1889
1890typedef struct XML_cp XML_Content;
1891
1892struct XML_cp {
1893  enum XML_Content_Type		type;
1894  enum XML_Content_Quant	quant;
1895  const XML_Char *		name;
1896  unsigned int			numchildren;
1897  XML_Content *			children;
1898};
1899</pre>
1900<p>Sets a handler for element declarations in a DTD. The handler gets
1901called with the name of the element in the declaration and a pointer
1902to a structure that contains the element model. It's the user code's
1903responsibility to free model when finished with it. See <code>
1904<a href="#XML_FreeContentModel">XML_FreeContentModel</a></code>.
1905There is no need to free the model from the handler, it can be kept
1906around and freed at a later stage.</p>
1907
1908<p>The <code>model</code> argument is the root of a tree of
1909<code>XML_Content</code> nodes. If <code>type</code> equals
1910<code>XML_CTYPE_EMPTY</code> or <code>XML_CTYPE_ANY</code>, then
1911<code>quant</code> will be <code>XML_CQUANT_NONE</code>, and the other
1912fields will be zero or <code>NULL</code>.  If <code>type</code> is
1913<code>XML_CTYPE_MIXED</code>, then <code>quant</code> will be
1914<code>XML_CQUANT_NONE</code> or <code>XML_CQUANT_REP</code> and
1915<code>numchildren</code> will contain the number of elements that are
1916allowed to be mixed in and <code>children</code> points to an array of
1917<code>XML_Content</code> structures that will all have type
1918XML_CTYPE_NAME with no quantification.  Only the root node can be type
1919<code>XML_CTYPE_EMPTY</code>, <code>XML_CTYPE_ANY</code>, or
1920<code>XML_CTYPE_MIXED</code>.</p>
1921
1922<p>For type <code>XML_CTYPE_NAME</code>, the <code>name</code> field
1923points to the name and the <code>numchildren</code> and
1924<code>children</code> fields will be zero and <code>NULL</code>. The
1925<code>quant</code> field will indicate any quantifiers placed on the
1926name.</p>
1927
1928<p>Types <code>XML_CTYPE_CHOICE</code> and <code>XML_CTYPE_SEQ</code>
1929indicate a choice or sequence respectively. The
1930<code>numchildren</code> field indicates how many nodes in the choice
1931or sequence and <code>children</code> points to the nodes.</p>
1932</div>
1933
1934<div class="handler">
1935<h4 id="XML_SetAttlistDeclHandler">XML_SetAttlistDeclHandler</h4>
1936<pre class="setter">
1937void XMLCALL
1938XML_SetAttlistDeclHandler(XML_Parser p,
1939                          XML_AttlistDeclHandler attdecl);
1940</pre>
1941<pre class="signature">
1942typedef void
1943(XMLCALL *XML_AttlistDeclHandler)(void           *userData,
1944                                  const XML_Char *elname,
1945                                  const XML_Char *attname,
1946                                  const XML_Char *att_type,
1947                                  const XML_Char *dflt,
1948                                  int            isrequired);
1949</pre>
1950<p>Set a handler for attlist declarations in the DTD. This handler is
1951called for <em>each</em> attribute. So a single attlist declaration
1952with multiple attributes declared will generate multiple calls to this
1953handler. The <code>elname</code> parameter returns the name of the
1954element for which the attribute is being declared. The attribute name
1955is in the <code>attname</code> parameter. The attribute type is in the
1956<code>att_type</code> parameter.  It is the string representing the
1957type in the declaration with whitespace removed.</p>
1958
1959<p>The <code>dflt</code> parameter holds the default value. It will be
1960<code>NULL</code> in the case of "#IMPLIED" or "#REQUIRED" attributes. You can
1961distinguish these two cases by checking the <code>isrequired</code>
1962parameter, which will be true in the case of "#REQUIRED" attributes.
1963Attributes which are "#FIXED" will have also have a true
1964<code>isrequired</code>, but they will have the non-<code>NULL</code> fixed value
1965in the <code>dflt</code> parameter.</p>
1966</div>
1967
1968<div class="handler">
1969<h4 id="XML_SetEntityDeclHandler">XML_SetEntityDeclHandler</h4>
1970<pre class="setter">
1971void XMLCALL
1972XML_SetEntityDeclHandler(XML_Parser p,
1973			 XML_EntityDeclHandler handler);
1974</pre>
1975<pre class="signature">
1976typedef void
1977(XMLCALL *XML_EntityDeclHandler)(void           *userData,
1978                                 const XML_Char *entityName,
1979                                 int            is_parameter_entity,
1980                                 const XML_Char *value,
1981                                 int            value_length,
1982                                 const XML_Char *base,
1983                                 const XML_Char *systemId,
1984                                 const XML_Char *publicId,
1985                                 const XML_Char *notationName);
1986</pre>
1987<p>Sets a handler that will be called for all entity declarations.
1988The <code>is_parameter_entity</code> argument will be non-zero in the
1989case of parameter entities and zero otherwise.</p>
1990
1991<p>For internal entities (<code>&lt;!ENTITY foo "bar"&gt;</code>),
1992<code>value</code> will be non-<code>NULL</code> and <code>systemId</code>,
1993<code>publicId</code>, and <code>notationName</code> will all be <code>NULL</code>.
1994The value string is <em>not</em> null-terminated; the length is
1995provided in the <code>value_length</code> parameter. Do not use
1996<code>value_length</code> to test for internal entities, since it is
1997legal to have zero-length values. Instead check for whether or not
1998<code>value</code> is <code>NULL</code>.</p> <p>The <code>notationName</code>
1999argument will have a non-<code>NULL</code> value only for unparsed entity
2000declarations.</p>
2001</div>
2002
2003<div class="handler">
2004<h4 id="XML_SetUnparsedEntityDeclHandler">XML_SetUnparsedEntityDeclHandler</h4>
2005<pre class="setter">
2006void XMLCALL
2007XML_SetUnparsedEntityDeclHandler(XML_Parser p,
2008                                 XML_UnparsedEntityDeclHandler h)
2009</pre>
2010<pre class="signature">
2011typedef void
2012(XMLCALL *XML_UnparsedEntityDeclHandler)(void *userData,
2013                                         const XML_Char *entityName,
2014                                         const XML_Char *base,
2015                                         const XML_Char *systemId,
2016                                         const XML_Char *publicId,
2017                                         const XML_Char *notationName);
2018</pre>
2019<p>Set a handler that receives declarations of unparsed entities. These
2020are entity declarations that have a notation (NDATA) field:</p>
2021
2022<div id="eg"><pre>
2023&lt;!ENTITY logo SYSTEM "images/logo.gif" NDATA gif&gt;
2024</pre></div>
2025<p>This handler is obsolete and is provided for backwards
2026compatibility.  Use instead <a href= "#XML_SetEntityDeclHandler"
2027>XML_SetEntityDeclHandler</a>.</p>
2028</div>
2029
2030<div class="handler">
2031<h4 id="XML_SetNotationDeclHandler">XML_SetNotationDeclHandler</h4>
2032<pre class="setter">
2033void XMLCALL
2034XML_SetNotationDeclHandler(XML_Parser p,
2035                           XML_NotationDeclHandler h)
2036</pre>
2037<pre class="signature">
2038typedef void
2039(XMLCALL *XML_NotationDeclHandler)(void *userData,
2040                                   const XML_Char *notationName,
2041                                   const XML_Char *base,
2042                                   const XML_Char *systemId,
2043                                   const XML_Char *publicId);
2044</pre>
2045<p>Set a handler that receives notation declarations.</p>
2046</div>
2047
2048<div class="handler">
2049<h4 id="XML_SetNotStandaloneHandler">XML_SetNotStandaloneHandler</h4>
2050<pre class="setter">
2051void XMLCALL
2052XML_SetNotStandaloneHandler(XML_Parser p,
2053                            XML_NotStandaloneHandler h)
2054</pre>
2055<pre class="signature">
2056typedef int
2057(XMLCALL *XML_NotStandaloneHandler)(void *userData);
2058</pre>
2059<p>Set a handler that is called if the document is not "standalone".
2060This happens when there is an external subset or a reference to a
2061parameter entity, but does not have standalone set to "yes" in an XML
2062declaration.  If this handler returns <code>XML_STATUS_ERROR</code>,
2063then the parser will throw an <code>XML_ERROR_NOT_STANDALONE</code>
2064error.</p>
2065</div>
2066
2067<h3><a name="position">Parse position and error reporting functions</a></h3>
2068
2069<p>These are the functions you'll want to call when the parse
2070functions return <code>XML_STATUS_ERROR</code> (a parse error has
2071occurred), although the position reporting functions are useful outside
2072of errors. The position reported is the byte position (in the original
2073document or entity encoding) of the first of the sequence of
2074characters that generated the current event (or the error that caused
2075the parse functions to return <code>XML_STATUS_ERROR</code>.)  The
2076exceptions are callbacks triggered by declarations in the document
2077prologue, in which case they exact position reported is somewhere in the
2078relevant markup, but not necessarily as meaningful as for other
2079events.</p>
2080
2081<p>The position reporting functions are accurate only outside of the
2082DTD.  In other words, they usually return bogus information when
2083called from within a DTD declaration handler.</p>
2084
2085<h4 id="XML_GetErrorCode">XML_GetErrorCode</h4>
2086<pre class="fcndec">
2087enum XML_Error XMLCALL
2088XML_GetErrorCode(XML_Parser p);
2089</pre>
2090<div class="fcndef">
2091Return what type of error has occurred.
2092</div>
2093
2094<h4 id="XML_ErrorString">XML_ErrorString</h4>
2095<pre class="fcndec">
2096const XML_LChar * XMLCALL
2097XML_ErrorString(enum XML_Error code);
2098</pre>
2099<div class="fcndef">
2100Return a string describing the error corresponding to code.
2101The code should be one of the enums that can be returned from
2102<code><a href= "#XML_GetErrorCode" >XML_GetErrorCode</a></code>.
2103</div>
2104
2105<h4 id="XML_GetCurrentByteIndex">XML_GetCurrentByteIndex</h4>
2106<pre class="fcndec">
2107XML_Index XMLCALL
2108XML_GetCurrentByteIndex(XML_Parser p);
2109</pre>
2110<div class="fcndef">
2111Return the byte offset of the position.  This always corresponds to
2112the values returned by <code><a href= "#XML_GetCurrentLineNumber"
2113>XML_GetCurrentLineNumber</a></code> and <code><a href=
2114"#XML_GetCurrentColumnNumber" >XML_GetCurrentColumnNumber</a></code>.
2115</div>
2116
2117<h4 id="XML_GetCurrentLineNumber">XML_GetCurrentLineNumber</h4>
2118<pre class="fcndec">
2119XML_Size XMLCALL
2120XML_GetCurrentLineNumber(XML_Parser p);
2121</pre>
2122<div class="fcndef">
2123Return the line number of the position.  The first line is reported as
2124<code>1</code>.
2125</div>
2126
2127<h4 id="XML_GetCurrentColumnNumber">XML_GetCurrentColumnNumber</h4>
2128<pre class="fcndec">
2129XML_Size XMLCALL
2130XML_GetCurrentColumnNumber(XML_Parser p);
2131</pre>
2132<div class="fcndef">
2133Return the offset, from the beginning of the current line, of
2134the position.
2135</div>
2136
2137<h4 id="XML_GetCurrentByteCount">XML_GetCurrentByteCount</h4>
2138<pre class="fcndec">
2139int XMLCALL
2140XML_GetCurrentByteCount(XML_Parser p);
2141</pre>
2142<div class="fcndef">
2143Return the number of bytes in the current event. Returns
2144<code>0</code> if the event is inside a reference to an internal
2145entity and for the end-tag event for empty element tags (the later can
2146be used to distinguish empty-element tags from empty elements using
2147separate start and end tags).
2148</div>
2149
2150<h4 id="XML_GetInputContext">XML_GetInputContext</h4>
2151<pre class="fcndec">
2152const char * XMLCALL
2153XML_GetInputContext(XML_Parser p,
2154                    int *offset,
2155                    int *size);
2156</pre>
2157<div class="fcndef">
2158
2159<p>Returns the parser's input buffer, sets the integer pointed at by
2160<code>offset</code> to the offset within this buffer of the current
2161parse position, and set the integer pointed at by <code>size</code> to
2162the size of the returned buffer.</p>
2163
2164<p>This should only be called from within a handler during an active
2165parse and the returned buffer should only be referred to from within
2166the handler that made the call. This input buffer contains the
2167untranslated bytes of the input.</p>
2168
2169<p>Only a limited amount of context is kept, so if the event
2170triggering a call spans over a very large amount of input, the actual
2171parse position may be before the beginning of the buffer.</p>
2172
2173<p>If <code>XML_CONTEXT_BYTES</code> is zero, this will always
2174return <code>NULL</code>.</p>
2175</div>
2176
2177<h3><a name="attack-protection">Attack Protection</a><a name="billion-laughs"></a></h3>
2178
2179<h4 id="XML_SetBillionLaughsAttackProtectionMaximumAmplification">XML_SetBillionLaughsAttackProtectionMaximumAmplification</h4>
2180<pre class="fcndec">
2181/* Added in Expat 2.4.0. */
2182XML_Bool XMLCALL
2183XML_SetBillionLaughsAttackProtectionMaximumAmplification(XML_Parser p,
2184                                                         float maximumAmplificationFactor);
2185</pre>
2186<div class="fcndef">
2187  <p>
2188    Sets the maximum tolerated amplification factor
2189    for protection against
2190    <a href="https://en.wikipedia.org/wiki/Billion_laughs_attack">billion laughs attacks</a>
2191    (default: <code>100.0</code>)
2192    of parser <code>p</code> to <code>maximumAmplificationFactor</code>, and
2193    returns <code>XML_TRUE</code> upon success and <code>XML_FALSE</code> upon error.
2194  </p>
2195
2196  The amplification factor is calculated as ..
2197  <pre>
2198    amplification := (direct + indirect) / direct
2199  </pre>
2200  .. while parsing, whereas
2201  <code>direct</code> is the number of bytes read from the primary document in parsing and
2202  <code>indirect</code> is the number of bytes added by expanding entities and reading of external DTD files, combined.
2203
2204  <p>For a call to <code>XML_SetBillionLaughsAttackProtectionMaximumAmplification</code> to succeed:</p>
2205  <ul>
2206    <li>parser <code>p</code> must be a non-<code>NULL</code> root parser (without any parent parsers) and</li>
2207    <li><code>maximumAmplificationFactor</code> must be non-<code>NaN</code> and greater than or equal to <code>1.0</code>.</li>
2208  </ul>
2209
2210  <p>
2211    <strong>Note:</strong>
2212    If you ever need to increase this value for non-attack payload,
2213    please <a href="https://github.com/libexpat/libexpat/issues">file a bug report</a>.
2214  </p>
2215
2216  <p>
2217    <strong>Note:</strong>
2218    Peak amplifications
2219    of factor 15,000 for the entire payload and
2220    of factor 30,000 in the middle of parsing
2221    have been observed with small benign files in practice.
2222
2223    So if you do reduce the maximum allowed amplification,
2224    please make sure that the activation threshold is still big enough
2225    to not end up with undesired false positives (i.e. benign files being rejected).
2226  </p>
2227</div>
2228
2229<h4 id="XML_SetBillionLaughsAttackProtectionActivationThreshold">XML_SetBillionLaughsAttackProtectionActivationThreshold</h4>
2230<pre class="fcndec">
2231/* Added in Expat 2.4.0. */
2232XML_Bool XMLCALL
2233XML_SetBillionLaughsAttackProtectionActivationThreshold(XML_Parser p,
2234                                                        unsigned long long activationThresholdBytes);
2235</pre>
2236<div class="fcndef">
2237  <p>
2238    Sets number of output bytes (including amplification from entity expansion and reading DTD files)
2239    needed to activate protection against
2240    <a href="https://en.wikipedia.org/wiki/Billion_laughs_attack">billion laughs attacks</a>
2241    (default: <code>8 MiB</code>)
2242    of parser <code>p</code> to <code>activationThresholdBytes</code>, and
2243    returns <code>XML_TRUE</code> upon success and <code>XML_FALSE</code> upon error.
2244  </p>
2245
2246  <p>For a call to <code>XML_SetBillionLaughsAttackProtectionActivationThreshold</code> to succeed:</p>
2247  <ul>
2248    <li>parser <code>p</code> must be a non-<code>NULL</code> root parser (without any parent parsers).</li>
2249  </ul>
2250
2251  <p>
2252    <strong>Note:</strong>
2253    If you ever need to increase this value for non-attack payload,
2254    please <a href="https://github.com/libexpat/libexpat/issues">file a bug report</a>.
2255  </p>
2256
2257  <p>
2258    <strong>Note:</strong>
2259    Activation thresholds below 4 MiB are known to break support for
2260    <a href="https://en.wikipedia.org/wiki/Darwin_Information_Typing_Architecture">DITA</a> 1.3 payload
2261    and are hence not recommended.
2262  </p>
2263</div>
2264
2265<h4 id="XML_SetReparseDeferralEnabled">XML_SetReparseDeferralEnabled</h4>
2266<pre class="fcndec">
2267/* Added in Expat 2.6.0. */
2268XML_Bool XMLCALL
2269XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled);
2270</pre>
2271<div class="fcndef">
2272  <p>
2273    Large tokens may require many parse calls before enough data is available for Expat to parse it in full.
2274    If Expat retried parsing the token on every parse call, parsing could take quadratic time.
2275    To avoid this, Expat only retries once a significant amount of new data is available.
2276    This function allows disabling this behavior.
2277  </p>
2278  <p>
2279    The <code>enabled</code> argument should be <code>XML_TRUE</code> or <code>XML_FALSE</code>.
2280  </p>
2281  <p>
2282    Returns <code>XML_TRUE</code> on success, and <code>XML_FALSE</code> on error.
2283  </p>
2284</div>
2285
2286<h3><a name="miscellaneous">Miscellaneous functions</a></h3>
2287
2288<p>The functions in this section either obtain state information from
2289the parser or can be used to dynamically set parser options.</p>
2290
2291<h4 id="XML_SetUserData">XML_SetUserData</h4>
2292<pre class="fcndec">
2293void XMLCALL
2294XML_SetUserData(XML_Parser p,
2295                void *userData);
2296</pre>
2297<div class="fcndef">
2298This sets the user data pointer that gets passed to handlers.  It
2299overwrites any previous value for this pointer. Note that the
2300application is responsible for freeing the memory associated with
2301<code>userData</code> when it is finished with the parser. So if you
2302call this when there's already a pointer there, and you haven't freed
2303the memory associated with it, then you've probably just leaked
2304memory.
2305</div>
2306
2307<h4 id="XML_GetUserData">XML_GetUserData</h4>
2308<pre class="fcndec">
2309void * XMLCALL
2310XML_GetUserData(XML_Parser p);
2311</pre>
2312<div class="fcndef">
2313This returns the user data pointer that gets passed to handlers.
2314It is actually implemented as a macro.
2315</div>
2316
2317<h4 id="XML_UseParserAsHandlerArg">XML_UseParserAsHandlerArg</h4>
2318<pre class="fcndec">
2319void XMLCALL
2320XML_UseParserAsHandlerArg(XML_Parser p);
2321</pre>
2322<div class="fcndef">
2323After this is called, handlers receive the parser in their
2324<code>userData</code> arguments.  The user data can still be obtained
2325using the <code><a href= "#XML_GetUserData"
2326>XML_GetUserData</a></code> function.
2327</div>
2328
2329<h4 id="XML_SetBase">XML_SetBase</h4>
2330<pre class="fcndec">
2331enum XML_Status XMLCALL
2332XML_SetBase(XML_Parser p,
2333            const XML_Char *base);
2334</pre>
2335<div class="fcndef">
2336Set the base to be used for resolving relative URIs in system
2337identifiers.  The return value is <code>XML_STATUS_ERROR</code> if
2338there's no memory to store base, otherwise it's
2339<code>XML_STATUS_OK</code>.
2340</div>
2341
2342<h4 id="XML_GetBase">XML_GetBase</h4>
2343<pre class="fcndec">
2344const XML_Char * XMLCALL
2345XML_GetBase(XML_Parser p);
2346</pre>
2347<div class="fcndef">
2348Return the base for resolving relative URIs.
2349</div>
2350
2351<h4 id="XML_GetSpecifiedAttributeCount">XML_GetSpecifiedAttributeCount</h4>
2352<pre class="fcndec">
2353int XMLCALL
2354XML_GetSpecifiedAttributeCount(XML_Parser p);
2355</pre>
2356<div class="fcndef">
2357When attributes are reported to the start handler in the atts vector,
2358attributes that were explicitly set in the element occur before any
2359attributes that receive their value from default information in an
2360ATTLIST declaration. This function returns the number of attributes
2361that were explicitly set times two, thus giving the offset in the
2362<code>atts</code> array passed to the start tag handler of the first
2363attribute set due to defaults. It supplies information for the last
2364call to a start handler. If called inside a start handler, then that
2365means the current call.
2366</div>
2367
2368<h4 id="XML_GetIdAttributeIndex">XML_GetIdAttributeIndex</h4>
2369<pre class="fcndec">
2370int XMLCALL
2371XML_GetIdAttributeIndex(XML_Parser p);
2372</pre>
2373<div class="fcndef">
2374Returns the index of the ID attribute passed in the atts array in the
2375last call to <code><a href= "#XML_StartElementHandler"
2376>XML_StartElementHandler</a></code>, or -1 if there is no ID
2377attribute. If called inside a start handler, then that means the
2378current call.
2379</div>
2380
2381<h4 id="XML_GetAttributeInfo">XML_GetAttributeInfo</h4>
2382<pre class="fcndec">
2383const XML_AttrInfo * XMLCALL
2384XML_GetAttributeInfo(XML_Parser parser);
2385</pre>
2386<pre class="signature">
2387typedef struct {
2388  XML_Index  nameStart;  /* Offset to beginning of the attribute name. */
2389  XML_Index  nameEnd;    /* Offset after the attribute name's last byte. */
2390  XML_Index  valueStart; /* Offset to beginning of the attribute value. */
2391  XML_Index  valueEnd;   /* Offset after the attribute value's last byte. */
2392} XML_AttrInfo;
2393</pre>
2394<div class="fcndef">
2395Returns an array of <code>XML_AttrInfo</code> structures for the
2396attribute/value pairs passed in the last call to the
2397<code>XML_StartElementHandler</code> that were specified
2398in the start-tag rather than defaulted. Each attribute/value pair counts
2399as 1; thus the number of entries in the array is
2400<code>XML_GetSpecifiedAttributeCount(parser) / 2</code>.
2401</div>
2402
2403<h4 id="XML_SetEncoding">XML_SetEncoding</h4>
2404<pre class="fcndec">
2405enum XML_Status XMLCALL
2406XML_SetEncoding(XML_Parser p,
2407                const XML_Char *encoding);
2408</pre>
2409<div class="fcndef">
2410Set the encoding to be used by the parser. It is equivalent to
2411passing a non-<code>NULL</code> encoding argument to the parser creation functions.
2412It must not be called after <code><a href= "#XML_Parse"
2413>XML_Parse</a></code> or <code><a href= "#XML_ParseBuffer"
2414>XML_ParseBuffer</a></code> have been called on the given parser.
2415Returns <code>XML_STATUS_OK</code> on success or
2416<code>XML_STATUS_ERROR</code> on error.
2417</div>
2418
2419<h4 id="XML_SetParamEntityParsing">XML_SetParamEntityParsing</h4>
2420<pre class="fcndec">
2421int XMLCALL
2422XML_SetParamEntityParsing(XML_Parser p,
2423                          enum XML_ParamEntityParsing code);
2424</pre>
2425<div class="fcndef">
2426This enables parsing of parameter entities, including the external
2427parameter entity that is the external DTD subset, according to
2428<code>code</code>.
2429The choices for <code>code</code> are:
2430<ul>
2431<li><code>XML_PARAM_ENTITY_PARSING_NEVER</code></li>
2432<li><code>XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE</code></li>
2433<li><code>XML_PARAM_ENTITY_PARSING_ALWAYS</code></li>
2434</ul>
2435<b>Note:</b> If <code>XML_SetParamEntityParsing</code> is called after
2436<code>XML_Parse</code> or <code>XML_ParseBuffer</code>, then it has
2437no effect and will always return 0.
2438</div>
2439
2440<h4 id="XML_SetHashSalt">XML_SetHashSalt</h4>
2441<pre class="fcndec">
2442int XMLCALL
2443XML_SetHashSalt(XML_Parser p,
2444                unsigned long hash_salt);
2445</pre>
2446<div class="fcndef">
2447Sets the hash salt to use for internal hash calculations.
2448Helps in preventing DoS attacks based on predicting hash
2449function behavior. In order to have an effect this must be called
2450before parsing has started. Returns 1 if successful, 0 when called
2451after <code>XML_Parse</code> or <code>XML_ParseBuffer</code>.
2452<p><b>Note:</b> This call is optional, as the parser will auto-generate
2453a new random salt value if no value has been set at the start of parsing.</p>
2454<p><b>Note:</b> One should not call <code>XML_SetHashSalt</code> with a
2455hash salt value of 0, as this value is used as sentinel value to indicate
2456that <code>XML_SetHashSalt</code> has <b>not</b> been called. Consequently
2457such a call will have no effect, even if it returns 1.</p>
2458</div>
2459
2460<h4 id="XML_UseForeignDTD">XML_UseForeignDTD</h4>
2461<pre class="fcndec">
2462enum XML_Error XMLCALL
2463XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);
2464</pre>
2465<div class="fcndef">
2466<p>This function allows an application to provide an external subset
2467for the document type declaration for documents which do not specify
2468an external subset of their own.  For documents which specify an
2469external subset in their DOCTYPE declaration, the application-provided
2470subset will be ignored.  If the document does not contain a DOCTYPE
2471declaration at all and <code>useDTD</code> is true, the
2472application-provided subset will be parsed, but the
2473<code>startDoctypeDeclHandler</code> and
2474<code>endDoctypeDeclHandler</code> functions, if set, will not be
2475called.  The setting of parameter entity parsing, controlled using
2476<code><a href= "#XML_SetParamEntityParsing"
2477>XML_SetParamEntityParsing</a></code>, will be honored.</p>
2478
2479<p>The application-provided external subset is read by calling the
2480external entity reference handler set via <code><a href=
2481"#XML_SetExternalEntityRefHandler"
2482>XML_SetExternalEntityRefHandler</a></code> with both
2483<code>publicId</code> and <code>systemId</code> set to <code>NULL</code>.</p>
2484
2485<p>If this function is called after parsing has begun, it returns
2486<code>XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING</code> and ignores
2487<code>useDTD</code>.  If called when Expat has been compiled without
2488DTD support, it returns
2489<code>XML_ERROR_FEATURE_REQUIRES_XML_DTD</code>.  Otherwise, it
2490returns <code>XML_ERROR_NONE</code>.</p>
2491
2492<p><b>Note:</b> For the purpose of checking WFC: Entity Declared, passing
2493<code>useDTD == XML_TRUE</code> will make the parser behave as if
2494the document had a DTD with an external subset. This holds true even if
2495the external entity reference handler returns without action.</p>
2496</div>
2497
2498<h4 id="XML_SetReturnNSTriplet">XML_SetReturnNSTriplet</h4>
2499<pre class="fcndec">
2500void XMLCALL
2501XML_SetReturnNSTriplet(XML_Parser parser,
2502                       int        do_nst);
2503</pre>
2504<div class="fcndef">
2505<p>
2506This function only has an effect when using a parser created with
2507<code><a href= "#XML_ParserCreateNS" >XML_ParserCreateNS</a></code>,
2508i.e. when namespace processing is in effect. The <code>do_nst</code>
2509sets whether or not prefixes are returned with names qualified with a
2510namespace prefix. If this function is called with <code>do_nst</code>
2511non-zero, then afterwards namespace qualified names (that is qualified
2512with a prefix as opposed to belonging to a default namespace) are
2513returned as a triplet with the three parts separated by the namespace
2514separator specified when the parser was created.  The order of
2515returned parts is URI, local name, and prefix.</p> <p>If
2516<code>do_nst</code> is zero, then namespaces are reported in the
2517default manner, URI then local_name separated by the namespace
2518separator.</p>
2519</div>
2520
2521<h4 id="XML_DefaultCurrent">XML_DefaultCurrent</h4>
2522<pre class="fcndec">
2523void XMLCALL
2524XML_DefaultCurrent(XML_Parser parser);
2525</pre>
2526<div class="fcndef">
2527This can be called within a handler for a start element, end element,
2528processing instruction or character data.  It causes the corresponding
2529markup to be passed to the default handler set by <code><a
2530href="#XML_SetDefaultHandler" >XML_SetDefaultHandler</a></code> or
2531<code><a href="#XML_SetDefaultHandlerExpand"
2532>XML_SetDefaultHandlerExpand</a></code>.  It does nothing if there is
2533not a default handler.
2534</div>
2535
2536<h4 id="XML_ExpatVersion">XML_ExpatVersion</h4>
2537<pre class="fcndec">
2538XML_LChar * XMLCALL
2539XML_ExpatVersion();
2540</pre>
2541<div class="fcndef">
2542Return the library version as a string (e.g. <code>"expat_1.95.1"</code>).
2543</div>
2544
2545<h4 id="XML_ExpatVersionInfo">XML_ExpatVersionInfo</h4>
2546<pre class="fcndec">
2547struct XML_Expat_Version XMLCALL
2548XML_ExpatVersionInfo();
2549</pre>
2550<pre class="signature">
2551typedef struct {
2552  int major;
2553  int minor;
2554  int micro;
2555} XML_Expat_Version;
2556</pre>
2557<div class="fcndef">
2558Return the library version information as a structure.
2559Some macros are also defined that support compile-time tests of the
2560library version:
2561<ul>
2562<li><code>XML_MAJOR_VERSION</code></li>
2563<li><code>XML_MINOR_VERSION</code></li>
2564<li><code>XML_MICRO_VERSION</code></li>
2565</ul>
2566Testing these constants is currently the best way to determine if
2567particular parts of the Expat API are available.
2568</div>
2569
2570<h4 id="XML_GetFeatureList">XML_GetFeatureList</h4>
2571<pre class="fcndec">
2572const XML_Feature * XMLCALL
2573XML_GetFeatureList();
2574</pre>
2575<pre class="signature">
2576enum XML_FeatureEnum {
2577  XML_FEATURE_END = 0,
2578  XML_FEATURE_UNICODE,
2579  XML_FEATURE_UNICODE_WCHAR_T,
2580  XML_FEATURE_DTD,
2581  XML_FEATURE_CONTEXT_BYTES,
2582  XML_FEATURE_MIN_SIZE,
2583  XML_FEATURE_SIZEOF_XML_CHAR,
2584  XML_FEATURE_SIZEOF_XML_LCHAR,
2585  XML_FEATURE_NS,
2586  XML_FEATURE_LARGE_SIZE
2587};
2588
2589typedef struct {
2590  enum XML_FeatureEnum  feature;
2591  XML_LChar            *name;
2592  long int              value;
2593} XML_Feature;
2594</pre>
2595<div class="fcndef">
2596<p>Returns a list of "feature" records, providing details on how
2597Expat was configured at compile time.  Most applications should not
2598need to worry about this, but this information is otherwise not
2599available from Expat.  This function allows code that does need to
2600check these features to do so at runtime.</p>
2601
2602<p>The return value is an array of <code>XML_Feature</code>,
2603terminated by a record with a <code>feature</code> of
2604<code>XML_FEATURE_END</code> and <code>name</code> of <code>NULL</code>,
2605identifying the feature-test macros Expat was compiled with.  Since an
2606application that requires this kind of information needs to determine
2607the type of character the <code>name</code> points to, records for the
2608<code>XML_FEATURE_SIZEOF_XML_CHAR</code> and
2609<code>XML_FEATURE_SIZEOF_XML_LCHAR</code> will be located at the
2610beginning of the list, followed by <code>XML_FEATURE_UNICODE</code>
2611and <code>XML_FEATURE_UNICODE_WCHAR_T</code>, if they are present at
2612all.</p>
2613
2614<p>Some features have an associated value.  If there isn't an
2615associated value, the <code>value</code> field is set to 0.  At this
2616time, the following features have been defined to have values:</p>
2617
2618<dl>
2619  <dt><code>XML_FEATURE_SIZEOF_XML_CHAR</code></dt>
2620  <dd>The number of bytes occupied by one <code>XML_Char</code>
2621  character.</dd>
2622  <dt><code>XML_FEATURE_SIZEOF_XML_LCHAR</code></dt>
2623  <dd>The number of bytes occupied by one <code>XML_LChar</code>
2624  character.</dd>
2625  <dt><code>XML_FEATURE_CONTEXT_BYTES</code></dt>
2626  <dd>The maximum number of characters of context which can be
2627  reported by <code><a href= "#XML_GetInputContext"
2628  >XML_GetInputContext</a></code>.</dd>
2629</dl>
2630</div>
2631
2632<h4 id="XML_FreeContentModel">XML_FreeContentModel</h4>
2633<pre class="fcndec">
2634void XMLCALL
2635XML_FreeContentModel(XML_Parser parser, XML_Content *model);
2636</pre>
2637<div class="fcndef">
2638Function to deallocate the <code>model</code> argument passed to the
2639<code>XML_ElementDeclHandler</code> callback set using <code><a
2640href="#XML_SetElementDeclHandler" >XML_ElementDeclHandler</a></code>.
2641This function should not be used for any other purpose.
2642</div>
2643
2644<p>The following functions allow external code to share the memory
2645allocator an <code>XML_Parser</code> has been configured to use.  This
2646is especially useful for third-party libraries that interact with a
2647parser object created by application code, or heavily layered
2648applications.  This can be essential when using dynamically loaded
2649libraries which use different C standard libraries (this can happen on
2650Windows, at least).</p>
2651
2652<h4 id="XML_MemMalloc">XML_MemMalloc</h4>
2653<pre class="fcndec">
2654void * XMLCALL
2655XML_MemMalloc(XML_Parser parser, size_t size);
2656</pre>
2657<div class="fcndef">
2658Allocate <code>size</code> bytes of memory using the allocator the
2659<code>parser</code> object has been configured to use.  Returns a
2660pointer to the memory or <code>NULL</code> on failure.  Memory allocated in this
2661way must be freed using <code><a href="#XML_MemFree"
2662>XML_MemFree</a></code>.
2663</div>
2664
2665<h4 id="XML_MemRealloc">XML_MemRealloc</h4>
2666<pre class="fcndec">
2667void * XMLCALL
2668XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);
2669</pre>
2670<div class="fcndef">
2671Allocate <code>size</code> bytes of memory using the allocator the
2672<code>parser</code> object has been configured to use.
2673<code>ptr</code> must point to a block of memory allocated by <code><a
2674href="#XML_MemMalloc" >XML_MemMalloc</a></code> or
2675<code>XML_MemRealloc</code>, or be <code>NULL</code>.  This function tries to
2676expand the block pointed to by <code>ptr</code> if possible.  Returns
2677a pointer to the memory or <code>NULL</code> on failure.  On success, the original
2678block has either been expanded or freed.  On failure, the original
2679block has not been freed; the caller is responsible for freeing the
2680original block.  Memory allocated in this way must be freed using
2681<code><a href="#XML_MemFree"
2682>XML_MemFree</a></code>.
2683</div>
2684
2685<h4 id="XML_MemFree">XML_MemFree</h4>
2686<pre class="fcndec">
2687void XMLCALL
2688XML_MemFree(XML_Parser parser, void *ptr);
2689</pre>
2690<div class="fcndef">
2691Free a block of memory pointed to by <code>ptr</code>.  The block must
2692have been allocated by <code><a href="#XML_MemMalloc"
2693>XML_MemMalloc</a></code> or <code>XML_MemRealloc</code>, or be <code>NULL</code>.
2694</div>
2695
2696<hr />
2697
2698  <div class="footer">
2699    Found a bug in the documentation?
2700    <a href="https://github.com/libexpat/libexpat/issues">Please file a bug report.</a>
2701  </div>
2702
2703</div>
2704</body>
2705</html>
2706