Ticket #5210: test_property_tree.cpp

File test_property_tree.cpp, 1.5 KB (added by anonymous, 11 years ago)
Line 
1#include <sstream>
2#include <iostream>
3#include "boost/foreach.hpp"
4#include "boost/property_tree/xml_parser.hpp"
5#include "boost/property_tree/json_parser.hpp"
6#include "boost/property_tree/ptree.hpp"
7#include "boost/property_tree/detail/xml_parser_writer_settings.hpp"
8
9using namespace boost::property_tree;
10using namespace std;
11
12
13void printLevel(stringstream & sout , const ptree& pt, const unsigned int indent = 0)
14{
15 BOOST_FOREACH(const ptree::value_type &v, pt)
16 {
17 string key = v.first;
18 string value = v.second.get_value("");
19 string indent_str = std::string( indent, ' ');
20 sout << indent_str << key << ": \"" << value <<"\"" << endl;
21 if(! v.second.empty() )
22 printLevel(sout, v.second, indent + 4);
23 }
24}
25
26void logPtree(const ptree& pt)
27{
28 stringstream ostream;
29 printLevel(ostream, pt);
30 cout <<ostream.str();
31}
32
33ptree readXml(const std::string & filename)
34{
35 ptree pt;
36 read_xml(filename, pt);
37 return pt;
38}
39
40std::string writeJson(const ptree & pt)
41{
42 std::stringstream result;
43 write_json(result, pt);
44 return result.str();
45}
46
47void cleanUpPtree(ptree & pt)
48{
49 // remove empty strings in nodes
50 BOOST_FOREACH(ptree::value_type &v, pt)
51 {
52 if(! v.second.empty() )
53 v.second.put_value("");
54 cleanUpPtree(v.second);
55 }
56}
57
58int main()
59{
60 ptree pt = readXml("Shop.xml");
61 logPtree(pt);
62 //cleanUpPtree(pt); // remove values from nodes with children
63 string json(writeJson(pt));
64 cout << json << endl;
65}