Search code examples
c++xmllibxml2

How can I use SAX interface of libxml2 to parse streamed xml file?


I have a requirement of parsing big xml files from server. We currently use a stream to read these file which looks like below:

class stream
{
    size_t getSize();
    size_t read(void* buf, size_t offset, size_t size);
}

But I could just find two interfaces:

XMLPUBFUN int XMLCALL
        xmlSAXUserParseFile (xmlSAXHandlerPtr sax,
                     void *user_data,
                     const char *filename);
XMLPUBFUN int XMLCALL
        xmlSAXUserParseMemory   (xmlSAXHandlerPtr sax,
                     void *user_data,
                     const char *buffer,
                     int size);

How can I solve this problem? Thanks.


Solution

  • Use libxml2's push parser interface. Initialize the parser by calling xmlCreatePushParserCtxt. Then read your data from the server and process it piece by piece with xmlParseChunk. This will invoke the SAX callbacks. Finally, free the parser context with xmlFreeParserCtxt.