我想使用 C 将 XML 文件读入 char *buffer
。
执行此操作的最佳方法是什么?
我应该如何开始?
最佳答案
如果您想解析 XML,而不仅仅是将其读入缓冲区(这不是特定于 XML 的东西,请参阅 Christoph 和 Baget 的回答),您可以使用例如 libxml2 :
#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;
}
在 Unix 机器上,您通常使用以下代码编译上面的内容:
% gcc -o read-xml $(xml2-config --cflags) -Wall $(xml2-config --libs) read-xml.c
关于c - 如何将 XML 文件读入 C 中的缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/381300/