欢迎交流,代码如下:
利用tinyxml库,tinyxml库的用法百度找把,别忘了工程下包含tinyxml文件(在工程的main.cpp那里添加tinyxml的.cpp文件)。
#include <iostream>
#include <io.h>
#include <boost/filesystem.hpp>
#include <vector>
#include <map>
#include"tinyxml.h"
#include"tinystr.h"
using namespace std;
namespace fs = boost::filesystem;
std::vector<string> res;
std::map<string, string> mapType;
//获取文件夹下所有文件带路径名称
int get_filenames(const std::string& dir, std::vector<std::string>& filenames)
{
fs::path path(dir);
if (!fs::exists(path))
{
return -1;
}
fs::directory_iterator end_iter;
for (fs::directory_iterator iter(path); iter != end_iter; ++iter)
{
if (fs::is_regular_file(iter->status()))
{
filenames.push_back(iter->path().string());
}
if (fs::is_directory(iter->status()))
{
get_filenames(iter->path().string(), filenames);
}
}
return filenames.size();
}
//字符串分割函数
vector<string> split(const string& str, const string& delim)
{
vector<string> res;
if ("" == str) return res;
//先将要切割的字符串从string类型转换为char*类型
char * strs = new char[str.length() + 1]; //不要忘了
strcpy(strs, str.c_str());
char * d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while (p) {
string s = p; //分割得到的字符串转换为string类型
res.push_back(s); //存入结果数组
p = strtok(NULL, d);
}
return res;
}
//读取.txt配置文件
void readTxt(string file)
{
std::ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
string line;
while (getline(infile, line))
{
res = split(line, "/");
cout << res[0] << endl;
// 用insert函数插入数据
mapType.insert(pair<string, string>(res[0], res[1]));
string new_name = mapType[res[0]];
cout << "old_name: " << res[0] << endl;
cout << "new_name: " << new_name << endl;
}
infile.close(); //关闭文件输入流
}
int main(int argc, char* argv[])
{
cout << "start!" << endl;
readTxt("C:\\Users\\admin\\Desktop\\1.txt");
vector<string> file;
std::string file_name;
get_filenames(argv[1], file);
for (int j = 0; j < file.size(); j++)
{
std::string file_name;
cout << "file[j]: " << file[j] << endl;
file_name = file[j];
cout << "file_name: " <<file_name << endl;
//读入一个xml文件
cout << "read .xml" << endl;
const char* p = file_name.data();
//创建一个XML的文档对象。
TiXmlDocument *myDocument = new TiXmlDocument(p);
myDocument->LoadFile();
//获得xml的头,即声明部分
TiXmlDeclaration* decl = myDocument->FirstChild()->ToDeclaration();
//获得根元素
TiXmlElement *RootElement = myDocument->RootElement();
cout << RootElement->Value() << endl;
TiXmlElement *First = RootElement->FirstChildElement("object");
while (First != nullptr)
{
TiXmlElement *First2 = First->FirstChildElement("name");
cout << First2->GetText() << endl;
std::string old_name = First2->GetText();
cout << "old_name: " << old_name << endl;
if (mapType[old_name] == "")
{
break;
}
First2->FirstChild()->SetValue(mapType[old_name].c_str());
cout << "new_name: " << First2->GetText() << endl;
First = First->NextSiblingElement("object");
}
myDocument->SaveFile();
}
return 0;
}