Linux下獲取xml除錯資訊等級
阿新 • • 發佈:2018-12-22
Linux下獲取XML除錯資訊等級
#ifndef _LOG_H_ #define _LOG_H_ #include <stdio.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlmemory.h> #include <libxml/xpath.h> #define CONF_FILE_NAME "/opt/can_book.xml" #define DEBUG_SON "debug" /* 除錯資訊的兒子節點 */ #define DEBUG_GRAND_SON_ATTR "debug_level_attr" /* 日誌資訊孫子節點 */ xmlChar *DebugLevelRead(void); // 獲取除錯資訊等級,預設除錯等級是4 #endif /* _LOG_H_ */
介面已經寫好,寫個小測試程式測試一下即可,親測可行。上面註釋部分是/opt/can_book.xml檔案。XML和JSON是常用的結構,掌握其解析方式很有必要,我是在ubuntu12.04中使用的。/*************************************************************** <?xml version="1.0" encoding="UTF-8" ?> <can_books> <debug> <debug_level debug_level_attr="4" /> </debug> <can0> <tag id="1"> <attr>ESL</attr> <goods>1</goods> </tag> </can0> </can_books> ***************************************************************/ #include "log.h" xmlChar *DebugLevelRead(void) { assert(CONF_FILE_NAME); xmlDocPtr doc = NULL; // 文件物件指標 xmlNodePtr root = NULL; // 根節點物件指標 // 讀入一個帶有"UTF-8"的xml文件,並返回一個文件指標 if((doc = xmlReadFile(CONF_FILE_NAME, "UTF-8", 256)) == NULL) { fprintf(stderr, "Failed to parse xml file:%s\n", CONF_FILE_NAME); return NULL; } // 獲得文件的根節點 if((root = xmlDocGetRootElement(doc)) == NULL) { fprintf(stderr, "Failed to get root node.\n"); goto FAILED; } xmlNodePtr cur = NULL; // 當前節點 -- 根節點的子節點 xmlNodePtr cur_grandson = NULL; // 當前節點的子節點 xmlChar *debug_level = NULL; // 除錯等級字串 cur = root->xmlChildrenNode; while(cur != NULL) { if(!xmlStrcmp(cur->name, (const xmlChar *)DEBUG_SON)) { cur_grandson = cur->xmlChildrenNode; debug_level = xmlGetProp(cur_grandson, (const xmlChar*)DEBUG_GRAND_SON_ATTR); // 讀取節點屬性 printf("debug_level = %s\r\n", debug_level); } cur = cur->next; } xmlSaveFormatFileEnc(CONF_FILE_NAME, doc, "UTF-8", 1); // 將文件以"UTF-8"格式進行儲存 xmlFreeDoc(doc); // 釋放文件指標 return debug_level; FAILED: if(doc) { xmlFreeDoc(doc); } return NULL; }