c语言xml字符串,C语言的XML解析器

expat和libxml2的两个示例。 第二个是恕我直言,易于使用,因为它在内存中创建了一个树,一个数据易于使用的结构。 另一方面,移民不需要构建任何东西(您必须自己做),它只允许您在解析期间在特定事件处调用处理程序。 但外籍人士可能是更快(我没有测量)。

使用expat,读取XML文件并显示缩进的元素:

/*

A simple test program to parse XML documents with expat

. It just displays the element

names.

On Debian, compile with:

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

Inspired from

*/

#include

#include

#include

/* 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);

}

使用libxml2,该程序可显示根元素的名称及其子代的名称:

/*

Simple test with libxml2 . 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

#include

#include

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 (%i)\n", root->name, root->type);

first_child = root->children;

for (node = first_child; node; node = node->next) {

fprintf(stdout, "\t Child is (%i)\n", node->name, node->type);

}

fprintf(stdout, "...\n");

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值