【问题标题】:boost::property_tree passing subtree including <xmlattr>boost::property_tree 传递子树,包括 <xmlattr>
【发布时间】:2017-07-15 18:17:39
【问题描述】:

我正在尝试将 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") 传递子树。这样做的缺点是函数无法访问该节点的&lt;xmlattr&gt;

如何通过树的这一部分访问&lt;xmlattr&gt;? 提前感谢您的任何想法。

~彼得

【问题讨论】:

  • &lt;xmlattr&gt; 没什么特别的,它只是一个子树。所以get_child("par2") 只返回一个具有&lt;xmlattr&gt; 子树的树。

标签: c++ boost ptree


【解决方案1】:

类型是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

【讨论】:

  • 像魅力一样工作。我之前尝试过实现这一点,但出于某些我不记得它不起作用的原因。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2019-02-10
相关资源
最近更新 更多