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

问题描述 投票:0回答:3

我花了很长时间才弄清楚如何使用 libxml2 的 sax 解析器。有人可以发布一个解析此 XML 的示例(是的,没有

<xml...>
页眉和页脚标签,如果可以由 libxml2 sax 解析器解析):

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

解析器应该打印出元素

hello
中包含的数据,并获取属性
foo
的值。

我正在研究这个例子,但希望其他人能抢先一步,因为我没有取得太大进展。 Google 尚未为 libxml2 sax 解析器提供任何完整的、有效的示例。

c++ c libxml2
3个回答
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;
}

这会产生输出:

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

0
投票

我可以建议rapidxml吗?


0
投票

@杰伊

请问您的链接中是否要表达以下内容:

RapidXml 试图创建尽可能最快的 XML 解析器,同时保留可用性、可移植性和合理的 W3C 兼容性。它是一个用现代 C++ 编写的原位解析器,解析速度接近对相同数据执行的 strlen 函数。

© www.soinside.com 2019 - 2024. All rights reserved.