Request a complete, compiled libxml2 sax example

I have damn time to figure out how to use the sax parser for libxml2. Can someone post an example that parses this XML (yes, without header and footer tags <xml...>, if that can be parsed by the libxml2 sax parser):

<hello foo="bar">world</hello>

The analyzer should print the data enclosed in the element hello, and also capture the attribute value foo.

I am working on this example, but I hope that someone else will hit me because I have not made much progress. Google has not given any complete, working examples for the parser libxml2 sax.

+3
source share
2 answers

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
+3
0

Source: https://habr.com/ru/post/1770116/


All Articles