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;
}
總結
以上是生活随笔為你收集整理的c语言xml字符串,C语言的XML解析器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网站服务器怎么用手机登录不了怎么办,怎么
- 下一篇: spring cloud微服务_年后进大