| 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 |
|
|---|
| 9 | using namespace boost::property_tree;
|
|---|
| 10 | using namespace std;
|
|---|
| 11 |
|
|---|
| 12 |
|
|---|
| 13 | void 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 |
|
|---|
| 26 | void logPtree(const ptree& pt)
|
|---|
| 27 | {
|
|---|
| 28 | stringstream ostream;
|
|---|
| 29 | printLevel(ostream, pt);
|
|---|
| 30 | cout <<ostream.str();
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | ptree readXml(const std::string & filename)
|
|---|
| 34 | {
|
|---|
| 35 | ptree pt;
|
|---|
| 36 | read_xml(filename, pt);
|
|---|
| 37 | return pt;
|
|---|
| 38 | }
|
|---|
| 39 |
|
|---|
| 40 | std::string writeJson(const ptree & pt)
|
|---|
| 41 | {
|
|---|
| 42 | std::stringstream result;
|
|---|
| 43 | write_json(result, pt);
|
|---|
| 44 | return result.str();
|
|---|
| 45 | }
|
|---|
| 46 |
|
|---|
| 47 | void 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 |
|
|---|
| 58 | int 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 | }
|
|---|