c++ json转xml
时间: 2023-07-30 18:06:12 浏览: 174
可以使用第三方库,比如RapidJSON。以下是一个示例:
```c++
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
#include <iostream>
#include <fstream>
using namespace rapidjson;
int main() {
// 读取JSON文件
std::ifstream ifs("example.json");
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
// 解析JSON
Document d;
d.Parse(content.c_str());
// 创建XML文档
rapidxml::xml_document<> doc;
// 创建根节点
rapidxml::xml_node<> *root = doc.allocate_node(rapidxml::node_element, "root");
doc.append_node(root);
// 将JSON转换为XML
for (Value::ConstMemberIterator itr = d.MemberBegin(); itr != d.MemberEnd(); ++itr) {
rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, itr->name.GetString());
root->append_node(node);
if (itr->value.IsObject()) {
for (Value::ConstMemberIterator itr2 = itr->value.MemberBegin(); itr2 != itr->value.MemberEnd(); ++itr2) {
rapidxml::xml_node<> *sub_node = doc.allocate_node(rapidxml::node_element, itr2->name.GetString());
sub_node->value(doc.allocate_string(itr2->value.GetString()));
node->append_node(sub_node);
}
} else if (itr->value.IsArray()) {
for (Value::ConstValueIterator itr2 = itr->value.Begin(); itr2 != itr->value.End(); ++itr2) {
rapidxml::xml_node<> *sub_node = doc.allocate_node(rapidxml::node_element, "item");
sub_node->value(doc.allocate_string(itr2->GetString()));
node->append_node(sub_node);
}
} else {
node->value(doc.allocate_string(itr->value.GetString()));
}
}
// 输出XML
std::string result;
rapidxml::print(std::back_inserter(result), doc, 0);
std::cout << result << std::endl;
return 0;
}
```
注意,代码中使用了RapidJSON和RapidXML两个库,需要先安装它们。
阅读全文