gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:21:05 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com