1. 程式人生 > >[C language] 利用libexpat 解析XML,簡單好用

[C language] 利用libexpat 解析XML,簡單好用

libexpat.so解析xml使用非常方便

著名的Wayland也使用了此庫解析XML,俗稱:協議protocol.

test_expat.c:

#include <stdio.h> #include <string> #include <iostream> #include <string.h>

#include "expat.h"

using namespace std;

#define XML_FMT_INT_MOD "l"

#define Max_STORAGE 0x200 static bool sectPrStart = false; char *pfind = NULL; static char nameget[100] ={0}; static void StartElementHandler(void *userData,const XML_Char *name,                                 const XML_Char **atts) {  //if(!strcmp(pfind,name))  {    sectPrStart = true;   for (int i = 0; atts[i] != 0; i += 2)   {    cout << "name: " << atts[i] << endl;    cout << "value: " << atts[i+1] << endl;   }  } }

static void EndElementHandler(void *userData,const XML_Char *name) {    //if(!strcmp(pfind,name))  {   sectPrStart = false;   sprintf(nameget,"copy %s",name);   cout << "End element name: " << nameget<< endl;   cout << "End element name: " << name << endl;  } }

static void CharacterDataHandler(void *userData,const XML_Char *s,                                  int len) {  if(sectPrStart && s)  {   string str(s,len);   cout << "inner Text: " << str << endl;  } }

int main(int argc, char *argv[]) {  cout << "Start............................." << endl;  int i = 0;  pfind = argv[2];

 XML_Parser parser = XML_ParserCreate(NULL);  XML_SetUserData(parser, &i);  XML_SetElementHandler(parser, &StartElementHandler,&EndElementHandler);  {   XML_SetCharacterDataHandler(parser,&CharacterDataHandler);  }

 int size_buf = Max_STORAGE;  void* buf = malloc(size_buf);     const char* file_path = argv[1];  FILE* file = fopen(file_path,"r");    int ret = 0;  while(!feof(file))  {   ret = fread(buf,1,size_buf,file);   cout << "ret: " << ret << endl;   if (XML_Parse(parser, (char*) buf, ret, 0) == XML_STATUS_ERROR)   {    fprintf(stderr, "%s at line %" XML_FMT_INT_MOD "u ->%s\n",      XML_ErrorString(XML_GetErrorCode(parser)),      XML_GetCurrentLineNumber(parser), file_path);    break;   }  }  //last call  XML_Parse(parser, (char*) 0, 0, 1);

 free(buf);  XML_ParserFree(parser);  fclose(file);  cout << "End............................." << endl;  return 0; }