【发布时间】: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 来访问<xmlattr>.time,但该值是使用child.second.data() 在字符串中检索的。
我也可以指定 value 的类型吗? child.second.get<int> 之类的东西,这样我就可以得到 ex int、double 等类型的值,而不是字符串。
【问题讨论】:
标签: c++ xml boost boost-propertytree