gunner4evr
gunner4evr

Reputation: 79

how to use contexts in SAX XML parsing in C++(using libxml2)?

I'm writing an xml parser application in C++ using libxml2 library. I use startElementNsSAX2Func to parse the elements and charactersSAXFunc to parse element values.

Signatures:

void    startElementNsSAX2Func  (void * ctx, const xmlChar * localname, const xmlChar * prefix, const xmlChar * URI, int nb_namespaces, const xmlChar ** namespaces, int nb_attributes, int nb_defaulted, const xmlChar ** attributes)
void    charactersSAXFunc(void * ctx, const xmlChar * ch, int len)

I want to make use of the ctx variable so that I can parse the xml document based on the order of the elements and I'm not sure how to do it. Any insight on this would be really helpful.

Also I couldn't find a good article on XML SAX parsing in C/C++. Does anyone know a good tutorial on this?

Thanks for your help!

Upvotes: 0

Views: 1213

Answers (1)

nwellnhof
nwellnhof

Reputation: 33658

The ctx argument of the SAX callbacks will hold the pointer that is passed as user_data to initialization functions like xmlCreatePushParserCtxt or xmlCreateIOParserCtxt:

xmlParserCtxtPtr xmlCreatePushParserCtxt (xmlSAXHandlerPtr sax, 
                                          void * user_data, 
                                          const char * chunk, 
                                          int size, 
                                          const char * filename)

It can be used to pass a pointer to an arbitrary user-defined structure. This structure will typically contain a state variable that can be used to determine the current position in the document tree.

A nice tutorial can be found here. It uses the deprecated SAX1 interface, but the SAX2 interface is similar.

Upvotes: 0

Related Questions