Earlier we talked about generating XML files, but how to parse XML files?
File to be parsed:
Code 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;
}
The effect is as follows:
Later, I will introduce to you the json format file and the generation and analysis of Json file by C/C++