最近项目有项递归目录,保存为xml的工作,运用了libxml2这个开源库,对xml进行了详细的理解。简单介绍下思路,就是递归所有目录和子文件,生成一颗正常的树,并将这棵树写如xml。功能简单,主要是记录下libxml的使用方法 废话少说,直接上代码
-
#include <stdio.h>
-
#include <dirent.h>
-
#include <stdlib.h>
-
#include <string.h>
-
#include <list>
-
#include <iostream>
-
#ifdef __cplusplus
-
extern "C"
-
{
-
#endif
-
#include <libxml/parser.h>
-
#include <libxml/tree.h>
-
#ifdef __cplusplus
-
}
-
#endif
-
-
struct node_t{ //递归树的结构,用的是儿子列表法
-
std::string name;
-
std::list<struct node_t*> pChild;
-
};
-
typedef struct node_t node;
-
-
node root;
-
xmlDocPtr doc = NULL;
-
xmlNodePtr root_node = NULL;
-
void List(const char *path, int level,node *parentnode,xmlNodePtr parentXmlNode)
-
{
-
struct dirent *ent = NULL;
-
DIR *pDir;
-
if((pDir = opendir(path)) != NULL)
-
{
-
while(NULL != (ent = readdir(pDir)))
-
{
-
node *tmpnode = new node;
-
if(!tmpnode)
-
{
-
std::cout<<"alloc node errorn";
-
return ;
-
}
-
-
xmlNodePtr tmpxmlnode;
-
-
if(ent->d_type == 8 && ent->d_name[0] != '.') // d_type:8-文件,4-目录
-
{
-
tmpnode->name = ent->d_name;
-
parentnode->pChild.push_back(tmpnode);
-
tmpxmlnode = xmlNewChild(parentXmlNode,NULL,BAD_CAST ent->d_name,BAD_CAST tmpnode->name.c_str());
-
}
-
else if(ent->d_name[0] != '.')
-
{
-
char *p = (char*)malloc(strlen(path) + strlen(ent->d_name) + 2);
-
strcpy(p, path);
-
strcat(p, "/");
-
strcat(p, ent->d_name);
-
tmpnode->name = p;
-
parentnode->pChild.push_back(tmpnode);
-
tmpxmlnode = xmlNewChild(parentXmlNode,NULL,BAD_CAST ent->d_name,BAD_CAST ent->d_name);
-
List(p, level+1, tmpnode, tmpxmlnode); // 递归遍历子目录
-
free(p);
-
}
-
}
-
closedir(pDir);
-
}
-
-
}
-
-
void testcase()
-
{
-
std::list<struct node_t*>::iterator itr = (*(*(*(root.pChild.begin()))->pChild.begin())->pChild.begin())->pChild.begin();
-
-
int num = root.pChild.size();
-
for(;itr != (*(*(*(root.pChild.begin()))->pChild.begin())->pChild.begin())->pChild.end(); itr++)
-
{
-
std::cout<<"path is "<<(*itr)->name<<std::endl;
-
}
-
}
-
-
int main()
-
{
-
std::string path = "/media/disk/ffmpeg-0.9.2/mytest";
-
root.name = path;
-
doc = xmlNewDoc(BAD_CAST "1.0");
-
root_node = xmlNewNode(NULL, BAD_CAST "root");
-
xmlDocSetRootElement(doc,root_node);
-
List(path.c_str(), 0, &root, root_node);
-
//testcase();
-
-
xmlSaveFormatFileEnc("test.xml",doc,"UTF-8",1);
-
if(doc)
-
{
-
xmlFreeDoc(doc);
-
}
-
xmlCleanupParser();
-
return 0;
-
}
阅读(3366) | 评论(0) | 转发(1) |