Analisador de XML para C [fechado]

pode sugerir algum do melhor processador XML para C ?

Author: coder, 2008-12-30

10 answers

Dois dos parsers mais utilizados sãoExpat elibxml .

Se não se importar de usar C++, também há Xerces-C++.

 36
Author: Chris Jester-Young, 2008-12-30 07:17:46

Dois exemplos com expat e libxml2. O segundo é, IMHO, muito mais fácil de usar, uma vez que cria uma árvore na memória, um dado estrutura com a qual é fácil trabalhar. por outro lado, exporta não construir nada (você tem que fazê-lo você mesmo), ele apenas permite que você os manipuladores de chamadas em eventos específicos durante o processamento. Mas a expatriação pode ser mais rápido (Eu não medi).

Com expat, lendo um ficheiro XML e mostrando os elementos indentados:

/* 
   A simple test program to parse XML documents with expat
   <http://expat.sourceforge.net/>. It just displays the element
   names.

   On Debian, compile with:

   gcc -Wall -o expat-test -lexpat expat-test.c  

   Inspired from <http://www.xml.com/pub/a/1999/09/expat/index.html> 
*/

#include <expat.h>
#include <stdio.h>
#include <string.h>

/* Keep track of the current level in the XML tree */
int             Depth;

#define MAXCHARS 1000000

void
start(void *data, const char *el, const char **attr)
{
    int             i;

    for (i = 0; i < Depth; i++)
        printf("  ");

    printf("%s", el);

    for (i = 0; attr[i]; i += 2) {
        printf(" %s='%s'", attr[i], attr[i + 1]);
    }

    printf("\n");
    Depth++;
}               /* End of start handler */

void
end(void *data, const char *el)
{
    Depth--;
}               /* End of end handler */

int
main(int argc, char **argv)
{

    char           *filename;
    FILE           *f;
    size_t          size;
    char           *xmltext;
    XML_Parser      parser;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        return (1);
    }
    filename = argv[1];
    parser = XML_ParserCreate(NULL);
    if (parser == NULL) {
        fprintf(stderr, "Parser not created\n");
        return (1);
    }
    /* Tell expat to use functions start() and end() each times it encounters
     * the start or end of an element. */
    XML_SetElementHandler(parser, start, end);
    f = fopen(filename, "r");
    xmltext = malloc(MAXCHARS);
    /* Slurp the XML file in the buffer xmltext */
    size = fread(xmltext, sizeof(char), MAXCHARS, f);
    if (XML_Parse(parser, xmltext, strlen(xmltext), XML_TRUE) ==
        XML_STATUS_ERROR) {
        fprintf(stderr,
            "Cannot parse %s, file may be too large or not well-formed XML\n",
            filename);
        return (1);
    }
    fclose(f);
    XML_ParserFree(parser);
    fprintf(stdout, "Successfully parsed %i characters in file %s\n", size,
        filename);
    return (0);
}

Com libxml2, um programa que mostra o nome do elemento raiz e os nomes dos seus filhos:

/*
   Simple test with libxml2 <http://xmlsoft.org>. It displays the name
   of the root element and the names of all its children (not
   descendents, just children).

   On Debian, compiles with:
   gcc -Wall -o read-xml2 $(xml2-config --cflags) $(xml2-config --libs) \
                    read-xml2.c    

*/

#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>

int
main(int argc, char **argv)
{
    xmlDoc         *document;
    xmlNode        *root, *first_child, *node;
    char           *filename;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
        return 1;
    }
    filename = argv[1];

    document = xmlReadFile(filename, NULL, 0);
    root = xmlDocGetRootElement(document);
    fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
    first_child = root->children;
    for (node = first_child; node; node = node->next) {
        fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
    }
    fprintf(stdout, "...\n");
    return 0;
}
 64
Author: bortzmeyer, 2009-01-02 18:29:00

Que tal um escrito emmontagem pura :-) não se esqueça de verificar osmarcos de referência .

 39
Author: codelogic, 2008-12-30 07:27:44

Você pode tentar ezxml -- é um analisador leve escrito inteiramente em C.

Para C++ pode verificar TinyXML++

 9
Author: Kasprzol, 2017-01-09 15:44:10

Http://www.minixml.org também é muito bom. Pequeno e apenas ANSI C.

 6
Author: singpolyma, 2009-02-27 18:09:19

A minha preferência pessoal élibxml2 . É muito fácil de usar, mas eu nunca me dei ao trabalho de referenciá-lo, como eu só o usei para o processamento de arquivos de configuração.

 4
Author: Michael Foukarakis, 2009-09-06 05:57:58
Pode dar alguma indicação de que plataformas está a escrever? Isto deve pesar muito no que é "melhor". Você pode encontrar uma biblioteca super 'xml-foo' que não envia comumente na maioria dos sistemas por padrão .. embora seja grande, a falta da biblioteca pode evitar (ou pelo menos) irritar os usuários. A maior parte das vezes, uso libxml2 .. porque o seu padrão ou fácil de instalar nas plataformas que eu alvo.

Como vê, 'best' também é determinado pela biblioteca estar disponível em as plataformas alvo.

 2
Author: Tim Post, 2008-12-30 07:33:24

Para c++ sugiro a utilização de CMarkup .

 2
Author: Zhang Zhiliang, 2012-09-13 06:26:15
Nas janelas, é nativo da API Win32...
 0
Author: , 2008-12-30 10:31:40