请求完整的可编译libxml2 sax示例

Ros*_*ers 4 c c++ libxml2

我花了点时间弄清楚如何为libxml2使用sax解析器。有人可以发布一个示例来解析此XML的示例吗(是的,没有<xml...>header和footer标记,如果可以由libxml2 sax解析器解析的话):

<hello foo="bar">world</hello>
Run Code Online (Sandbox Code Playgroud)

解析器应打印出元素中包含的数据,hello并获取attribute的值foo

我正在研究这个示例,但是希望别人能击败我,因为我没有取得太大进步。Google尚未提供libxml2 sax解析器的任何完整有效的示例。

Ros*_*ers 5

改编自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;
}
Run Code Online (Sandbox Code Playgroud)

产生输出:

Beginning of element : hello 
attribute: foo=bar
attribute: baz=baa
XML Document is well formed
Run Code Online (Sandbox Code Playgroud)

在Ubuntu 10.04.1上使用以下命令编译:

g++ -I/usr/include/libxml2 libxml2_hello_world.cpp /usr/lib/libxml2.a -lz\
    -o libxml2_hello_world
Run Code Online (Sandbox Code Playgroud)