從http://julp.developpez.com/c/libxml2/?page=sax
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
void start_element_callback(void *user_data, const xmlChar *name, const xmlChar **attrs) {
printf("Beginning of element : %s \n", name);
while (NULL != attrs && NULL != attrs[0]) {
printf("attribute: %s=%s\n",attrs[0],attrs[1]);
attrs = &attrs[2];
}
}
int main() {
const char* xml_path = "hello_world.xml";
FILE *xml_fh = fopen(xml_path,"w+");
fputs("<hello foo=\"bar\" baz=\"baa\">world</hello>",xml_fh);
fclose(xml_fh);
// Initialize all fields to zero
xmlSAXHandler sh = { 0 };
// register callback
sh.startElement = start_element_callback;
xmlParserCtxtPtr ctxt;
// create the context
if ((ctxt = xmlCreateFileParserCtxt(xml_path)) == NULL) {
fprintf(stderr, "Erreur lors de la création du contexte\n");
return EXIT_FAILURE;
}
// register sax handler with the context
ctxt->sax = &sh;
// parse the doc
xmlParseDocument(ctxt);
// well-formed document?
if (ctxt->wellFormed) {
printf("XML Document is well formed\n");
} else {
fprintf(stderr, "XML Document isn't well formed\n");
//xmlFreeParserCtxt(ctxt);
return EXIT_FAILURE;
}
// free the memory
// xmlFreeParserCtxt(ctxt);
return EXIT_SUCCESS;
}
改編這將產生輸出:
Beginning of element : hello
attribute: foo=bar
attribute: baz=baa
XML Document is well formed
編譯在Ubuntu 10.04.1以下命令:
g++ -I/usr/include/libxml2 libxml2_hello_world.cpp /usr/lib/libxml2.a -lz\
-o libxml2_hello_world
http://stackoverflow.com/問題/ 982716/libxml2-sax-parsing-and-ampersand – DumbCoder 2010-10-18 14:42:39
http://www.xmlsoft.org/exam ples/index.html#reader1.c – DumbCoder 2010-10-18 14:43:39
感謝您的鏈接。我認爲規範的Hello World仍然非常有用。我還需要從文件而不是內存解析。我在法國網站上發現了一個,我正在嘗試使其適用於在最新版本的ubuntu中找到的libxml2的當前版本。 – 2010-10-18 16:58:03