mardi 17 avril 2018

Iterate through boost property tree to generate YAML file recursively

For instance i have a yaml file with a complex tree structure as shown here

run:
  type: exercise
  entities:
    start_run:
      distance: 45
    end_run:
      distance: 56 

I am using boost property tree just as a container and Yaml-CPP library for writing.

What have i done so far:

//private member variable
YAML::Node m_node;

void SomeClass::treeIterator(const boost::property_tree::ptree& tree, const std::string& key)
{
     for (const auto& item : tree)
     {
        if (!key.empty())
        {
            m_node[key][item.first] = item.second.data();
        }
        if (!item.second.empty())
        {
             treeIterator(item.second, key + "." + item.first);
        }
    }
}

In the above code i try to iterate through the tree and fill the yaml node recursively. Ofcourse, i get a wrong tree structure when i print the node to a yaml file.

Idea:

I came up with an idea to fill the yaml node based on the key concatenated with delimiter like a . with all the parent nodes and dynamically generate childs for the yaml node respectively.

What do i want:

I want to write the whole yaml node based on the number of delimiters in the key

 if(key = "run.entities.start_run")
 {
     /* Do some delimiter extraction process*/
     while ((pos = key.find(delimiter)) != std::string::npos) 
     {
            token = key.substr(0, pos);
            key.erase(0, pos + delimiter.length());
     } 

      m_node[//here i want to add as many "token" found dynamically to the node]

      //In this case it should be generated like this
      m_node["run"]["entities"]["start_run"]
 }

Not sure how i can implement this dynamically to fill yaml node recursively. Is there a better way to achieve this using recursion?

Aucun commentaire:

Enregistrer un commentaire