c++ - 访问属性树中的多值键

标签 c++ xml boost boost-propertytree

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

我引用了 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;
        }
    }
 }

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

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

最佳答案

我建议 get_value<> :

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

关于c++ - 访问属性树中的多值键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40393765/

相关文章:

后端iOS动态应用流控

c++ - 为什么 uBLAS 没有 `operator*(matrix, vector)` ?

c++ - 如何访问 boost 文件系统路径类的字符串表示,并删除引号

c# - 为什么我的 C++ 代码看不到这个 C# 类成员?

c# - 如何制作固定的十六进制编辑器?

c++ - `long` 是否保证至少为 32 位?

c++ - boost::asio::io_service::run() 实际上做了什么?

使用另一个 cpp 项目中定义的函数的 C++ 静态库

php - 按字典顺序比较XPath中的两个字符串

java - 测试 TestNG 中所有包中的所有 JUnit 文件