I want to fill a boost::property_tree::ptree with the data from a xml, the xml format is in a string which I passed to stringstream and then I try to read it with read_xml, but the ptree data is null or empty when I look at the object while debugging, my code:
std::stringstream ss;
ss << "<?xml ?><root><test /></root>";
boost::property_tree::ptree pt;
boost::property_tree::xml_parser::read_xml( ss, pt);
result:
pt {m_data="" m_children=0x001dd3b0 }
before I had a string with this xml code:
<?xml version="1.0"?><Response Location="910" RequesterId="12" SequenceNumber="0">
<Id>1</Id>
<Type>P</Type>
<StatusMessage></StatusMessage>
<Message>Error</Message>
</Response>
But nothing works using visual studio with c++.
There is no data associated with root node so m_data
is empty but there is a child node (test) and m_children != nullptr
.
Please consider this example:
#include <sstream>
#include <string>
#include <boost/property_tree/xml_parser.hpp>
int main()
{
std::stringstream ss;
ss << "<?xml ?><root><test /></root>";
boost::property_tree::ptree pt;
boost::property_tree::xml_parser::read_xml(ss, pt);
// There is no data associated with root node...
std::string s(pt.get<std::string>("root"));
std::cout << "EXAMPLE1" << std::endl << "Data associated with root node: " << s << std::endl;
// ...but there is a child node.
std::cout << "Children of root node: ";
for (auto r : pt.get_child("root"))
std::cout << r.first << std::endl;
std::cout << std::endl << std::endl;
std::stringstream ss2;
ss2 << "<?xml ?><root>dummy</root>";
boost::property_tree::xml_parser::read_xml(ss2, pt);
// This time we have a string associated with root node
std::string s2(pt.get<std::string>("root"));
std::cout << "EXAMPLE2" << std::endl << "Data associated with root node: " << s2 << std::endl;
return 0;
}
It'll print:
EXAMPLE1
Data associated with root node:
Children of root node: test
EXAMPLE2
Data associated with root node: dummy
(http://coliru.stacked-crooked.com/a/34a99abb0aca78f2).
The Boost propertytree library doesn’t fully document its capabilities, but a good guide for parsing XML with Boost is http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/