6

How can I read this YAML file with yaml-cpp:

sensors:
  - id: 5
    hardwareId: 28-000005a32133
    type: 1
  - id: 6
    hardwareId: 28-000005a32132
    type: 4

I can't understand how can I get sensors item, to use it.

As I understand sensors is a YAML::Node. How can I get it?

Update 1:

YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& node_test1 = confg["sensors"];

for (std::size_t i = 0; i < node_test1.size(); i++) {
    const YAML::Node& node_test2 = node_test1[i];
    std::cout << "Id: " << node_test2["id"].as<std::string>() << std::endl;
    std::cout << "hardwareId: " << node_test2["hardwareId"].as<std::string>() << std::endl << std::endl;
}

This code works, but it was writed using tutorial about old api. I think this code could be rewrited with iterators, but I don't now how.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Dm3Ch
  • 621
  • 1
  • 10
  • 26
  • What have you tried? Read the tutorial: https://github.com/jbeder/yaml-cpp/wiki/Tutorial and see if that helps :) – Jesse Beder Jul 12 '15 at 14:20
  • I have read this tuttorial, I found how to read sequence, but iI didn't find how to read sequence that in the item. As I understand in my example `sensors` is also node. But i didn't found how to use it as `YAML::Node` – Dm3Ch Jul 12 '15 at 14:24

1 Answers1

8

It looks like your code works, but if you want to rewrite it with iterators, you can:

YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& sensors = config["sensors"];
for (YAML::iterator it = sensors.begin(); it != sensors.end(); ++it) {
    const YAML::Node& sensor = *it;
    std::cout << "Id: " << sensor["id"].as<std::string>() << "\n";
    std::cout << "hardwareId: " << sensor["hardwareId"].as<std::string>() << "\n\n";
}
Jesse Beder
  • 33,081
  • 21
  • 109
  • 146