3
* synopsis: Parse an XML document chunk by chunk to a tree and free it
4
* purpose: Demonstrate the use of xmlCreatePushParserCtxt() and
5
* xmlParseChunk() to read an XML file progressively
6
* into a tree and and xmlFreeDoc() to free the resulting tree
7
* usage: parse4 test3.xml
8
* test: parse4 test3.xml
9
* author: Daniel Veillard
10
* copy: see Copyright for the status of this software.
14
#include <libxml/parser.h>
15
#include <libxml/tree.h>
17
#ifdef LIBXML_PUSH_ENABLED
22
* @mem: array to store the packet
23
* @size: the packet size
25
* read at most @size bytes from the document and store it in @mem
27
* Returns the number of bytes read
30
readPacket(char *mem, int size) {
33
res = fread(mem, 1, size, desc);
39
* @filename: a filename or an URL
41
* Parse the resource and free the resulting tree
44
example4Func(const char *filename) {
45
xmlParserCtxtPtr ctxt;
47
xmlDocPtr doc; /* the resulting document tree */
51
* Read a few first byte to check the input used for the
52
* encoding detection at the parser level.
54
res = readPacket(chars, 4);
56
fprintf(stderr, "Failed to parse %s\n", filename);
61
* Create a progressive parsing context, the 2 first arguments
62
* are not used since we want to build a tree and not use a SAX
63
* parsing interface. We also pass the first bytes of the document
64
* to allow encoding detection when creating the parser but this
67
ctxt = xmlCreatePushParserCtxt(NULL, NULL,
68
chars, res, filename);
70
fprintf(stderr, "Failed to create parser context !\n");
75
* loop on the input getting the document data, of course 4 bytes
76
* at a time is not realistic but allows to verify testing on small
79
while ((res = readPacket(chars, 4)) > 0) {
80
xmlParseChunk(ctxt, chars, res, 0);
84
* there is no more input, indicate the parsing is finished.
86
xmlParseChunk(ctxt, chars, 0, 1);
89
* collect the document back and if it was wellformed
90
* and destroy the parser context.
93
res = ctxt->wellFormed;
94
xmlFreeParserCtxt(ctxt);
97
fprintf(stderr, "Failed to parse %s\n", filename);
101
* since we don't use the document, destroy it now.
106
int main(int argc, char **argv) {
111
* this initialize the library and check potential ABI mismatches
112
* between the version it was compiled for and the actual shared
118
* simulate a progressive parsing using the input file.
120
desc = fopen(argv[1], "rb");
122
example4Func(argv[1]);
125
fprintf(stderr, "Failed to parse %s\n", argv[1]);
129
* Cleanup function for the XML library.
133
* this is to debug memory for regression tests
138
#else /* ! LIBXML_PUSH_ENABLED */
139
int main(int argc, char **argv) {
140
fprintf(stderr, "Library not compiled with push parser support\n");