2

我正在尝试将 boost::property_tree::ptree 的元素传递给函数。详细地说,我必须遵循初始化 ptree 的 XML 代码:

<Master Name='gamma'>
    <Par1 Name='name1'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par1>
    <Par2 Name='name2'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par2>
</Master>

我想将它的一部分传递给一个函数。基本上我想通过:

   <Par2 Name='name2'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par2>

该函数可能如下所示:

 void processTree( which_type_do_I_put_here element ){
     std::string n = element.get<std::string>("<xmlattr>.Name");
     double val = element.get<double>("Value");
 }

一般来说,我可以使用ptree::get_child("par2"). 这样做的缺点是该函数无法访问<xmlattr>该节点。

如何通过访问树的这一部分<xmlattr>?提前感谢您的任何想法。

〜彼得

4

1 回答 1

3

类型是ptree.

一般来说,我可以使用 ptree::get_child("par2") 传递子树。

的确。

这样做的缺点是该函数无法访问该节点

那是不对的:

Live On Coliru

#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

std::string const sample = R"(
<Master Name='gamma'>
    <Par1 Name='name1'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par1>
    <Par2 Name='name2'>
        <Value>0.</Value>
        <Fix>1</Fix>
    </Par2>
</Master>
)";

using boost::property_tree::ptree;

void processTree(ptree const& element) {
     std::string n = element.get<std::string>("<xmlattr>.Name");

     double val = element.get<double>("Value");
     std::cout << __FUNCTION__ << ": n=" << n << " val=" << val << "\n";
}

int main() {
    ptree pt;
    {
        std::istringstream iss(sample);
        read_xml(iss, pt);
    }

    processTree(pt.get_child("Master.Par2"));
}

哪个打印:

processTree: n=name2 val=0
于 2017-02-24T21:02:49.933 回答