【问题标题】:Accessing multi-valued keys in Property Tree访问属性树中的多值键
【发布时间】:2016-11-03 04:12:15
【问题描述】:

我正在尝试在属性树中查询多值键。

我参考了this SO link

这是我的一段 Xml:

<Element type="MyType">
<Name type="Number">
<KeyFrame time="0">1920</KeyFrame>
<KeyFrame time="3000">1080</KeyFrame>
<KeyFrame time="4000">720</KeyFrame>
</Name>
</Element>

以下是代码:

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

using boost::property_tree::ptree;

int main() {
    std::stringstream ss("<Element type=\"MyType\">" 
    "<Name type=\"Number\">"
    "<KeyFrame time=\"0\">1920</KeyFrame>"
    "<KeyFrame time=\"3000\">1080</KeyFrame>" 
    "<KeyFrame time=\"4000\">720</KeyFrame></Name>" 
    "</Element>");

    ptree pt;
    boost::property_tree::read_xml(ss, pt);
   
    auto& root =  pt.get_child("Element");
    for (auto& child : root.get_child("Name"))
    {
        if(child.first == "KeyFrame")
        {
            std::cout<<child.second.get<int>("<xmlattr>.time", 0)<<" : "<<child.second.data()<<std::endl;
        }
    }
 }

在这里,我可以通过指定类型int 来访问&lt;xmlattr&gt;.time,但该值是使用child.second.data() 在字符串中检索的。

我也可以指定 value 的类型吗? child.second.get&lt;int&gt; 之类的东西,这样我就可以得到 ex int、double 等类型的值,而不是字符串。

【问题讨论】:

    标签: c++ xml boost boost-propertytree


    【解决方案1】:

    我建议get_value&lt;&gt;:

    Live On Coliru

    #include <boost/property_tree/ptree.hpp>
    #include <boost/property_tree/xml_parser.hpp>
    #include <iostream>
    #include <sstream>
    
    std::string const sample = R"(<Element type="MyType">
        <Name type="Number">
            <KeyFrame time="0">1920</KeyFrame>
            <KeyFrame time="3000">1080</KeyFrame>
            <KeyFrame time="4000">720</KeyFrame>
        </Name>
    </Element>)";
    
    using boost::property_tree::ptree;
    
    int main() {
      std::stringstream ss(sample);
    
      ptree pt;
      boost::property_tree::read_xml(ss, pt);
    
      auto &root = pt.get_child("Element");
      for (auto &child : root.get_child("Name")) {
        if (child.first == "KeyFrame") {
            auto node = child.second;
            std::cout << node.get<int>("<xmlattr>.time", 0) << " : "
                      << node.get_value<int>() << std::endl;
        }
      }
    }
    

    打印

    0 : 1920
    3000 : 1080
    4000 : 720
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多