C/C++解析XML格式文件
程序员文章站
2022-03-11 23:01:43
前面我们讲了生成XML文件, 但是 XML文件怎么解析呢?要解析的文件:代码Demo#include #include #include #include #include using namespace std;static int Debug = 1;int main(int argc, const char*...
前面我们讲了生成XML文件, 但是 XML文件怎么解析呢?
要解析的文件:
代码Demo
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <mxml.h>
using namespace std;
static int Debug = 1;
int main(int argc, const char* argv[])
{
if(argc != 2){
fprintf(stderr, "./a.out dest_name\n");
exit(-1);
}
FILE* rfp;
int count = 0;
while(!(rfp = fopen(argv[1], "r")) && count < 5){
fprintf(stderr, "file open error %d\n", ++count);
}
if(count == 5){
exit(-2);
}
if(Debug) printf("file:%s, rfp:%p, count:%d\n", argv[1], rfp, count);
mxml_node_t* root = NULL;
mxml_node_t* people = NULL;
mxml_node_t* object = NULL;
mxml_node_t* name = NULL;
mxml_node_t* age = NULL;
mxml_node_t* sex = NULL;
people = mxmlLoadFile(NULL, rfp, MXML_NO_CALLBACK); // 根标签
object = mxmlFindElement(people, people, "object", NULL, NULL, MXML_DESCEND);
while(object){
name = mxmlWalkNext(object, root, MXML_DESCEND_FIRST);
printf("attr:%s, name:%s\n", mxmlElementGetAttr(name, "report"),
mxmlGetText(name, 0));
age = mxmlWalkNext(name, root, MXML_NO_DESCEND);
printf("attr:%s, age:%s\n", mxmlElementGetAttr(age, "year"),
mxmlGetText(age, 0));
sex = mxmlWalkNext(age, root, MXML_NO_DESCEND);
printf("age:%s\n", mxmlGetText(sex, 0));
object = mxmlFindElement(object, people, "object", NULL, NULL, MXML_NO_DESCEND);
}
return 0;
}
效果如下:
后面 我将给大家介绍一下 json格式的文件 以及 C/C++对Json文件的生成和解析
本文地址:https://blog.csdn.net/qq_44065088/article/details/107356945