切换主题
C++ JSON & XML解析
JSON++
简介
JSON++ 是一个轻量级的 C++ JSON 解析库,支持 JSON 的解析和生成,适合嵌入式和高性能场景。
安装与使用
- 下载 JSON++ 源码并将其包含到项目中。
- 在代码中包含头文件:cpp
#include "json.hpp"
1
示例代码
以下是一个解析和生成 JSON 的示例:
cpp
#include <iostream>
#include "json.hpp"
int main() {
// 解析 JSON 字符串
std::string jsonStr = R"({"name": "Alice", "age": 25})";
json::JSON obj = json::JSON::Load(jsonStr);
std::cout << "Name: " << obj["name"].ToString() << std::endl;
std::cout << "Age: " << obj["age"].ToInt() << std::endl;
// 生成 JSON 对象
json::JSON newObj;
newObj["city"] = "New York";
newObj["population"] = 8419000;
std::cout << "Generated JSON: " << newObj.dump() << std::endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
注意事项
- 确保 JSON 数据格式正确,否则解析可能失败。
- 使用
try-catch
捕获异常以处理解析错误。
libxml++
简介
libxml++ 是基于 libxml2 的 C++ 封装库,提供了更易用的接口,用于解析和生成 XML。
安装与使用
- 安装 libxml++:
- 在 Linux 上使用包管理器安装:bash
sudo apt-get install libxml++2.6-dev
1 - 在 Windows 上通过 vcpkg 安装:bash
vcpkg install libxml++
1
- 在 Linux 上使用包管理器安装:
- 在代码中包含头文件:cpp
#include <libxml++/libxml++.h>
1
示例代码
以下是一个解析和生成 XML 的示例:
cpp
#include <iostream>
#include <libxml++/libxml++.h>
int main() {
// 解析 XML 字符串
std::string xmlStr = R"(<person><name>Alice</name><age>25</age></person>)";
xmlpp::DomParser parser;
parser.parse_memory(xmlStr);
if (auto root = parser.get_document()->get_root_node()) {
std::cout << "Root node: " << root->get_name() << std::endl;
for (auto child : root->get_children()) {
if (auto element = dynamic_cast<xmlpp::Element*>(child)) {
std::cout << element->get_name() << ": " << element->get_child_text()->get_content() << std::endl;
}
}
}
// 生成 XML 文档
auto doc = xmlpp::Document::create();
auto root = doc->create_root_node("city");
root->set_attribute("name", "New York");
root->add_child("population")->add_child_text("8419000");
std::cout << "Generated XML: " << doc->write_to_string() << std::endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
注意事项
- 确保安装了 libxml++ 的依赖库(如 libxml2)。
- 使用 UTF-8 编码处理 XML 数据,避免字符集问题。