在Linux下编写应用平台经常会面临编写各类配置文件,这里给出一种编写XML格式配置文件的编程方法。这段代码是基于libxml2库,通过调用库里面的相关函数生成各个配置节点,并保存配置文件:
相关代码如下:
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main(int argc, char **argv)
{
xmlDocPtr xmlDoc = NULL;
xmlNodePtr rootNode = NULL;
xmlNodePtr childNode = NULL;
// 制作version1.0 以及确认根节点
xmlDoc = xmlNewDoc(BAD_CAST "1.0");
rootNode = xmlNewNode(NULL, BAD_CAST "Config");
xmlDocSetRootElement(xmlDoc, rootNode);
// 构建数据库配置
xmlNewChild(rootNode, NULL, BAD_CAST "DBIP",BAD_CAST "127.0.0.1");
xmlNewChild(rootNode, NULL, BAD_CAST "DBPort",BAD_CAST "3306");
xmlNewChild(rootNode, NULL, BAD_CAST "DBUser",BAD_CAST "root");
xmlNewChild(rootNode, NULL, BAD_CAST "DBPass",BAD_CAST "test");
xmlNewChild(rootNode, NULL, BAD_CAST "DBName",BAD_CAST "CloudMon_DB");
// 构建数据库控制
childNode=xmlNewChild(rootNode, NULL, BAD_CAST "DBControl",BAD_CAST "1");
xmlNewProp(childNode, BAD_CAST "run", BAD_CAST "1");
// 加入有关KVM的控制信息
xmlNewChild(rootNode, NULL, BAD_CAST "KVMIP",BAD_CAST "127.0.0.1");
xmlNewChild(rootNode, NULL, BAD_CAST "KVMUser",BAD_CAST "root");
xmlNewChild(rootNode, NULL, BAD_CAST "KVMPass",BAD_CAST "test");
// 构建KVM控制
childNode=xmlNewChild(rootNode, NULL, BAD_CAST "KVMControl",BAD_CAST "1");
xmlNewProp(childNode, BAD_CAST "run", BAD_CAST "1");
// 加入描述信息
childNode = xmlNewNode(NULL, BAD_CAST "Information");
xmlAddChild(childNode, xmlNewText(BAD_CAST"Other Information"));
xmlAddChild(rootNode, childNode);
// 写入配置文件
xmlSaveFormatFileEnc("kvmconfig.xml",xmlDoc, "UTF-8", 1);
xmlFreeDoc(xmlDoc);
xmlCleanupParser();
xmlMemoryDump();
return(0);
}
编译命令:[root@kvm XMLParse]#gcc -I/usr/include/libxml2/ -lxml2 XMLParse.c -o xml
执行命令:[root@kvm XMLParse]#./xml
查看生成文件:[root@kvm XMLParse]# cat kvmconfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<Config>
<DBIP>127.0.0.1</DBIP>
<DBPort>3306</DBPort>
<DBUser>root</DBUser>
<DBPass>test</DBPass>
<DBName>CloudMon_DB</DBName>
<DBControl run="1">1</DBControl>
<KVMIP>127.0.0.1</KVMIP>
<KVMUser>root</KVMUser>
<KVMPass>test</KVMPass>
<KVMControl run="1">1</KVMControl>
<Information>Other Information</Information>
</Config>