fork download
  1. #include <iostream> /* C++ iostream C++98/11 */
  2. #include <string> /* C++ strings C++98/11 */
  3.  
  4. #include <boost/property_tree/ptree.hpp>
  5. #include <boost/property_tree/json_parser.hpp>
  6. #include <boost/property_tree/xml_parser.hpp>
  7.  
  8. namespace {
  9. std::string xml2json(const std::string& iXMLString) {
  10. boost::property_tree::ptree aPtree;
  11.  
  12. std::stringstream aXMLStream;
  13. std::stringstream aJSONStream;
  14.  
  15. aXMLStream << iXMLString;
  16. boost::property_tree::read_xml(aXMLStream, aPtree, boost::property_tree::xml_parser::trim_whitespace);
  17.  
  18. boost::property_tree::json_parser::write_json(aJSONStream, aPtree);
  19. return aJSONStream.str();
  20. }
  21. }
  22.  
  23. int main() {
  24. 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>";
  25. std::cout << xml2json(aXMLString);
  26. return 0;
  27. }
  28.  
Success #stdin #stdout 0.01s 5436KB
stdin
Standard input is empty
stdout
{
    "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"
                }
            }
        }
    }
}