Parsing mappings

#include <x/yaml/mappingnode.H>

switch (n->nodetype) {

// ...
case YAML_MAPPING_NODE:
    handle_mapping(x::yaml::mappingnode(n));
    break;

// ...
};

// ...

void handle_mapping(const x::yaml::mappingnode &n)
{
    size_t n=map->size();
    std::cout << n << " elements" << std::endl;
    for (size_t i=0; i<n; ++i)
    {
        std::pair<x::yaml::scalarnode, x::yaml::scalarnode> value=map->get(i);
        std::cout << value.first << "=" << value.second << std::endl;
    }
}

x::yaml::mappingnode refers to a subclass of x::yaml::nodeObj that represents a mapping in a YAML document. Its size() method gives the number of values in the mapping. get() returns a std::pair<x::yaml::node,x::yaml::node> giving the key and the value of a single mapping. Individually, the key or the value can be converted to another x::yaml::scalarnode, x::yaml::sequencenode, or an x::yaml::mappingnode, according to their nodetypes.

void dump(const x::yaml::mappingnode &map)
{
    for (std::pair<x::yaml::scalarnode, x::yaml::scalarnode> value: *map)
    {
        std::cout << value.first << "=" << value.second << std::endl;
    }
}

The referenced mapping object implements a begin() and an end() that return x::yaml::mappingnode::base::iterators over std::pair<x::yaml::node,x::yaml::node>s in the mapping. This example iterates over a mapping whose keys and values are expected to consist entirely of x::yaml::scalarnodes, so the range iteration value gets coerced accordingly. An exception gets thrown in the event of a type conversion failure if the mapping contains a different node for a key or a value.

void dump(const INSERT_LIBX_NAMESPACE::yaml::mappingnode &map)
{
    seq->for_each([]
         (x::yaml::scalarnode &&key, x::yaml::scalarnode &&value)
         {
             std::cout << value.first << "=" << value.second << std::endl;
         });
}

The for_each() method produces slightly more efficient code that iterates over the mapping, and invokes the functor or the lambda argument passing the key and the value of each individual mapping by rvalue.

Note

Mappings do not have to be mono-typed. The same mapping may contain a mixture of x::yaml::scalarnodes and x::yaml::sequencenodes, for example, for its keys and values. In this case, the range iteration or the for_each() should take a x::yaml::node rvalue, then proceed based on its nodetype.