I am trying to query multi-valued keys in Property Tree.
I have taken the reference from this SO link.
Here is a piece of my Xml:
<Element type="MyType">
<Name type="Number">
<KeyFrame time="0">1920</KeyFrame>
<KeyFrame time="3000">1080</KeyFrame>
<KeyFrame time="4000">720</KeyFrame>
</Name>
</Element>
Following is the code :
#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;
}
}
}
Here I am able to access the <xmlattr>.time
by specifying the type int
but the value is retrieved in a string using child.second.data()
.
Can I specify the type for value as well? something like child.second.get<int>
, So that I get the value in its type for ex int, double etc. and not as a string.
I'd suggest get_value<>
:
#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;
}
}
}
Prints
0 : 1920
3000 : 1080
4000 : 720