|
#include <fcntl.h> |
|
#include <unistd.h> |
|
#include <stdarg.h> |
|
#include <libxml/parser.h> |
|
|
|
#define VERBOSE 0 |
|
|
|
int readCallback(void * ctx, char * buffer, int len) |
|
{ |
|
int fd = *(int*)ctx; |
|
ssize_t read_length ; |
|
|
|
read_length = read(fd, buffer, (size_t)len); |
|
#if VERBOSE |
|
fprintf(stderr, "readCallback: read %ld bytes (of %d)\n", read_length, len); |
|
#endif |
|
return read_length; |
|
} |
|
|
|
int closeCallback(void * ctx) |
|
{ |
|
#if VERBOSE |
|
fprintf(stderr, "closeCallback\n"); |
|
#endif |
|
return 0; |
|
} |
|
|
|
void startDocCallback(void * ctx) |
|
{ |
|
#if VERBOSE |
|
fprintf(stderr, "startDocCallback\n"); |
|
#endif |
|
} |
|
|
|
void endDocCallback(void * ctx) |
|
{ |
|
#if VERBOSE |
|
fprintf(stderr, "endDocCallback\n"); |
|
#endif |
|
} |
|
|
|
void charactersCallback(void * ctx, const xmlChar * ch, int len) |
|
{ |
|
#if VERBOSE |
|
fprintf(stderr, "charactersCallback: received %d characters\n", len); |
|
#endif |
|
} |
|
|
|
#define ERROR_MESSAGE_LENGTH 256 |
|
void errorCallback(void *ctx, const char *msg, ...) |
|
{ |
|
char message[ERROR_MESSAGE_LENGTH]; |
|
va_list arg_ptr; |
|
|
|
va_start(arg_ptr, msg); |
|
vsnprintf(message, ERROR_MESSAGE_LENGTH, msg, arg_ptr); |
|
va_end(arg_ptr); |
|
|
|
fprintf(stderr, "errorCallback: %s", message); |
|
} |
|
|
|
void parse(char* filename) |
|
{ |
|
int fd; |
|
fd = open(filename, O_RDONLY, 0); |
|
fprintf(stderr, "parse: file %s\n", filename); |
|
|
|
xmlSAXHandler handler = { 0 } ; |
|
handler.startDocument = &startDocCallback; |
|
handler.endDocument = &endDocCallback; |
|
handler.characters = &charactersCallback; |
|
handler.error = &errorCallback; |
|
|
|
xmlParserCtxtPtr ctxt; |
|
ctxt = xmlCreateIOParserCtxt(NULL, NULL, |
|
(xmlInputReadCallback)readCallback, |
|
(xmlInputCloseCallback)closeCallback, |
|
(void *)(&fd), |
|
XML_CHAR_ENCODING_UTF8); |
|
ctxt->sax = &handler; |
|
xmlParseDocument(ctxt); |
|
} |
|
|
|
void main() |
|
{ |
|
parse("ok.xml"); |
|
parse("fail.xml"); |
|
} |