windows平台使用yaml-cpp解析yaml配置文件
code:https://github.com/jbeder/yaml-cpp
YAML 是一种类似XML和JSON一样的配置文件语言
YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言),是专门用来写配置文件的语言,相比 JSON 更加简洁和方便阅读。
下载yaml-cpp项目后在cmake中配置项目
勾选YAML_BUILD_SHARED_LIBS,生成动态链接库。
先前尝试只生成静态链接库,使用时会出现无法解析的外部符号无法链接的问题。
Configuring done
Generating done
打开构建好的yaml-cpp项目
编译生成yaml-cpp.lib和yaml-cpp.dll
#include "yaml-cpp/yaml.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
YAML::Node config = YAML::LoadFile("../config.yaml");
cout << "Node type " << config.Type() << endl;
cout << "skills type " << config["skills"].Type() << endl;
cout << "name:" << config["name"].as<string>() << endl;
cout << "sex:" << config["sex"].as<string>() << endl;
cout << "age:" << config["age"].as<int>() << endl;
cout << "skills c++:" << config["skills"]["c++"].as<int>() << endl;
cout << "skills java:" << config["skills"]["java"].as<int>() << endl;
cout << "skills android:" << config["skills"]["android"].as<int>() << endl;
cout << "skills python:" << config["skills"]["python"].as<int>() << endl;
for (YAML::const_iterator it = config["skills"].begin();
it != config["skills"].end(); ++it) {
cout << it->first.as<string>() << ":" << it->second.as<int>() << endl;
}
YAML::Node test1 = YAML::Load("[1,2,3,4]");
cout << " Type: " << test1.Type() << endl;
YAML::Node test2 = YAML::Load("1");
cout << " Type: " << test2.Type() << endl;
YAML::Node test3 = YAML::Load("{'id':1,'degree':'senior'}");
cout << " Type: " << test3.Type() << endl;
ofstream fout("testconfig.xml");
config["score"] = 99;
fout << config;
fout.close();
return 0;
}
新建一个项目对yaml-cpp库进行测试,解析config.yaml文件
name: frank
sex: male
age: 18
skills:
c++: 1
java: 1
android: 1
python: 1
在测试项目的附加包含目录、附加库目录、附加依赖项中加入yaml-cpp,将yaml-cpp.dll拷贝到测试项目中,编译运行。