1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| #include "yaml-cpp/yaml.h"
#include <cassert> #include <iostream> #include <vector> #include <fstream>
int main(int argc, char **argv) {
YAML::Node node; assert(node.IsNull()); node["key"] = "value"; if (node["key2"]) std::cout << node["key2"].as<std::string>() << std::endl; assert(node.IsMap()); node["seq"].push_back("first element"); node["seq"].push_back("second element"); assert(node["seq"].IsSequence());
YAML::Node node2; node2.push_back("first item"); node2.push_back("second item"); node2.push_back("third item"); assert(node2.IsSequence()); std::vector<int> v = {1, 3, 5, 7, 9}; node2.push_back(v); assert(node2.IsSequence()); assert(node2[0].as<std::string>() == "first item"); for (auto value : node2) { if (value.Type() == YAML::NodeType::Scalar) { std::cout << value.as<std::string>() << std::endl; } else if (value.Type() == YAML::NodeType::Sequence) { for (auto value2 : value) { std::cout << value2.as<int>() << std::endl; } } }
std::cout << "========1=========" << std::endl; node2["key"] = "value"; assert(node2.IsMap()); assert(node2[0].as<std::string>() == "first item"); node["node2"] = node2; node["pointer_to_first_element"] = node["seq"][0]; assert(node["pointer_to_first_element"].as<std::string>() == "first element"); node["seq"].remove(0); node.remove("pointer_to_first_element"); std::cout << node << std::endl;
std::ofstream file_out("/mnt/d/code/sylar/bin/conf/test.yaml"); file_out << node << std::endl; file_out.close(); std::cout << "========2=========" << std::endl;
std::ifstream file_in("/mnt/d/code/sylar/bin/conf/test.yaml"); YAML::Node node3 = YAML::Load(file_in); std::cout << node3 << std::endl; file_in.close(); std::cout << "========3=========" << std::endl;
YAML::Node node4 = YAML::LoadFile("/mnt/d/code/sylar/bin/conf/test.yaml"); std::cout << node4["node2"] << std::endl; std::cout << "========4=========" << std::endl;
for (auto it = node4.begin(); it != node4.end(); it++) { std::cout << it->first << it->second << std::endl; }
return 0; }
|