使用pugixml解析XML节点并转换为nlohmann::json对象

xml转json


#include <iostream>
#include <fstream>
#include <json.hpp>
#include <pugixml.hpp>

// 使用pugixml解析XML节点并转换为nlohmann::json对象
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 {
                // 如果JSON对象中已存在同名键且其值为字符串,转换为数组
                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);

    // 输出转换后的JSON对象
    std::cout << json_obj.dump(4) << std::endl;

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追Star仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值