#include <iostream> /* C++ iostream C++98/11 */ #include <string> /* C++ strings C++98/11 */ #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> namespace { std::string xml2json(const std::string& iXMLString) { boost::property_tree::ptree aPtree; std::stringstream aXMLStream; std::stringstream aJSONStream; aXMLStream << iXMLString; boost::property_tree::read_xml(aXMLStream, aPtree, boost::property_tree::xml_parser::trim_whitespace); boost::property_tree::json_parser::write_json(aJSONStream, aPtree); return aJSONStream.str(); } } int main() { std::string aXMLString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><farm> <cluster id = \"0\" weight = \"512\"> <node id = \"0\" status = \"UP\" connection = \"CDH_00\"/> <node id = \"1\" status = \"UP\" connection = \"CDH_01\"/> </cluster> <cluster id = \"1\" weight = \"512\"> <node id = \"0\" status = \"UP\" connection = \"CDH_10\"/> <node id = \"1\" status = \"UP\" connection = \"CDH_11\"/> </cluster></farm>"; std::cout << xml2json(aXMLString); return 0; }
Standard input is empty
{ "farm": { "cluster": { "<xmlattr>": { "id": "0", "weight": "512" }, "node": { "<xmlattr>": { "id": "0", "status": "UP", "connection": "CDH_00" } }, "node": { "<xmlattr>": { "id": "1", "status": "UP", "connection": "CDH_01" } } }, "cluster": { "<xmlattr>": { "id": "1", "weight": "512" }, "node": { "<xmlattr>": { "id": "0", "status": "UP", "connection": "CDH_10" } }, "node": { "<xmlattr>": { "id": "1", "status": "UP", "connection": "CDH_11" } } } } }