大家好,这几天我使用minixml 3.1库解析了xml格式数据,由于是头一次使用,且时间比较紧,总结的比较简陋。
libmxml.so解析xml数据时的内存布局如下图,以下面简单例子说明:
加载方式为:mxmlLoadString(NULL, pacData, MXML_OPAQUE_CALLBACK);
采用 MXML_OPAQUE_CALLBACK方式,跟采用MXML_NO_CALLBACK、MXML_TEXT_CALLBACK方式是不一样的
解析代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <iconv.h> 5 #include "mxml.h" 6 7 #define EL_RESP "Response" 8 #define EL_CMDTYPE "CmdType" 9 #define EL_NAME "Name" 10 #define EL_DEVICEID "DeviceID" 11 12 int parsexml(char *pacData) 13 { 14 mxml_node_t *root = mxmlLoadString(NULL, pacData, MXML_OPAQUE_CALLBACK); 15 mxml_node_t *resp = mxmlFindElement(root, root, EL_RESP, NULL, NULL, MXML_DESCEND_FIRST); 16 mxml_node_t *node = NULL; 17 char* pkey[] = { EL_CMDTYPE, EL_NAME, EL_DEVICEID }; 18 int i = 0, icount =sizeof(pkey) / sizeof(pkey[0]); 19 node = mxmlFindElement(resp, root, pkey[0], NULL, NULL, MXML_DESCEND_FIRST); 20 for(; i < icount; i++) 21 { 22 mxml_node_t* child = mxmlGetFirstChild(node); 23 const char* pvalue = mxmlGetOpaque(node); 24 const char* pvalue1 = mxmlGetOpaque(child); 25 printf("*** %d. %s:[%s] [%s] ", i+1, pkey[i], pvalue, pvalue1); 26 node = mxmlFindElement(node, root, pkey[i + 1], NULL, NULL, MXML_NO_DESCEND); 27 } 28 29 return 0; 30 } 31 32 int main(int argc, char* argv[]) 33 { 34 char *cfgpath = "./ljt.xml"; 35 FILE* pfile = fopen(cfgpath, "r"); 36 if(NULL == pfile) 37 { 38 printf("*** failed to open file %s ", cfgpath); 39 return 0; 40 } 41 char acData[1500] = { 0 }; 42 fseek(pfile, 0, SEEK_END); 43 long long llsize = ftell(pfile); 44 fseek(pfile, 0, SEEK_SET); 45 fread(acData, llsize, 1, pfile); 46 fclose(pfile); 47 printf("*** filesize = %lld ", llsize); 48 printf("%s ", acData); 49 50 parsexml(acData); 51 52 return 0; 53 }