1 #include <boost/optional.hpp>
2 #include <boost/property_tree/ptree.hpp>
3 #include <boost/property_tree/xml_parser.hpp>
10 static inline void addSubArray(Json::Value &d,
const std::string &key,
const Json::Value &arr) {
11 if (arr.size() == 0) {
13 }
else if (arr.size() == 1) {
20 static const int MAX_DEPTH = 10;
22 static inline Json::Value treeJson(
const boost::property_tree::ptree &tree,
int depth = 0) {
23 namespace bpt = boost::property_tree;
25 if (depth > MAX_DEPTH) {
26 throw std::runtime_error(
"parse error");
35 Json::Value list = Json::Value(Json::arrayValue);
38 for (
auto it = tree.ordered_begin(); it != tree.not_found(); it++) {
39 const std::string &val = it->first;
40 const bpt::ptree &subtree = it->second;
44 if (val ==
"<xmlattr>") {
45 for (
const bpt::ptree::value_type &attr : subtree) {
46 output[std::string(
"@") + attr.first] = attr.second.data();
53 }
else if (cur.key != val) {
54 addSubArray(output, cur.key, cur.list);
57 cur.list = Json::Value(Json::arrayValue);
59 cur.list.append(treeJson(subtree, depth + 1));
63 addSubArray(output, cur.key, cur.list);
67 auto val = tree.get_value_optional<std::string>();
68 if (!!val && val.get() !=
"") {
74 output[
"#text"] = val.get();
82 static inline Json::Value xml2json(std::istream &is) {
83 namespace bpt = boost::property_tree;
87 bpt::read_xml(is, pt, bpt::xml_parser::trim_whitespace);
90 throw std::runtime_error(
"parse error");
94 }
catch (std::exception &e) {
95 throw std::runtime_error(
"parse error");