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_ */
/***************************************************************
<?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;
}
接口已经写好,写个小测试程序测试一下即可,亲测可行。上面注释部分是/opt/can_book.xml文件。XML和JSON是常用的结构,掌握其解析方式很有必要,我是在ubuntu12.04中使用的。