简体   繁体   English

ptree get_value 名称包含“.”

[英]ptree get_value with name including “.”

"A": "1"
"A.B": "2"
"A.C": "3"

How to get the value of AB if i iterate through the ptree it works.如果我遍历它工作的 ptree,如何获得AB的值。 if i try to get value of pt.get_child("A\\.B").get_value<std::string>() .如果我尝试获取pt.get_child("A\\.B").get_value<std::string>() i get the following exception我收到以下异常

terminate called after throwing an instance of boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::ptree_bad_path> >'
      what():  No such node

please find the complete code below请在下面找到完整的代码

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
#include <string>
#include <iterator>

using boost::property_tree::ptree;

/* Indent Json Output */
std::string indent(int level) {
    std::string s;
    for (int i = 0; i < level; i++) s += "  ";
    return s;
}

/* Print tree in json format */
void printTree(ptree & pt, int level) {
    if (pt.empty()) {
        std::cerr << "\"" << pt.data() << "\"";
    } else {
        if (level) std::cerr << std::endl;
        std::cerr << indent(level) << "{" << std::endl;
        for (ptree::iterator pos = pt.begin(); pos != pt.end();) {
            std::cerr << indent(level + 1) << "\"" << pos-> first << "\": ";

            printTree(pos->second, level + 1);
            ++pos;
            if (pos != pt.end()) {
                std::cerr << ",";
            }
            std::cerr << std::endl;
        }
        std::cerr << indent(level) << " }";
    }
    return;
}

int main()
{
ptree pt;
read_ini("sample.ini", pt);
printTree(pt, 0);
std::cout << pt.get_child("A.B").get_value<std::string>() << std::endl; //tries to resolve A.B to two nodes    
std::cout << pt.get_child("A\\.B").get_value<std::string>() << std::endl; //error

}

sample.ini示例文件

A=1
A.B=2
A.C=3

You can use alternative path delimiters, but it's a bit tricky and not very well documented.可以使用替代路径分隔符,但这有点棘手,而且没有很好的文档记录。

You have to temporarily specify an alternative path separator:您必须临时指定替代路径分隔符:

Live On Coliru 住在 Coliru

#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
using boost::property_tree::ptree;

int main() {
    ptree pt;

    pt.put("a.b", "first");
    pt.put(ptree::path_type("a|complicated.name", '|'), "second");

    write_ini(std::cout, pt);
}

Prints印刷

[a]
b=first
complicated.name=second

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM