xml转json
#include <iostream>
#include <fstream>
#include <json.hpp>
#include <pugixml.hpp>
nlohmann::json xml_to_json(pugi::xml_node node) {
nlohmann::json json_node;
for (auto attr = node.first_attribute(); attr; attr = attr.next_attribute()) {
json_node[attr.name()] = attr.value();
}
for (auto child = node.first_child(); child; child = child.next_sibling()) {
std::string name = child.name();
if (child.type() == pugi::xml_node_type::node_pcdata) {
if (!json_node.contains(name)) {
json_node[name] = child.text().get();
} else {
if (json_node[name].is_string()) {
nlohmann::json arr;
arr.push_back(json_node[name]);
arr.push_back(child.text().get());
json_node[name] = arr;
} else {
json_node[name].push_back(child.text().get());
}
}
} else if (child.type() == pugi::xml_node_type::node_element) {
nlohmann::json child_json = xml_to_json(child);
if (json_node.contains(name) && json_node[name].is_array()) {
json_node[name].push_back(child_json);
} else if (json_node.contains(name)) {
nlohmann::json arr;
arr.push_back(json_node[name]);
arr.push_back(child_json);
json_node[name] = arr;
} else {
json_node[name] = child_json;
}
}
}
return json_node;
}
int main() {
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file("C:\\Users\\lenovo\\Desktop\\testQ.xml");
if (!result) {
std::cerr << "Error parsing XML file!\n";
return 1;
}
nlohmann::json json_obj = xml_to_json(doc);
std::cout << json_obj.dump(4) << std::endl;
return 0;
}