1.rapidXML介绍
RapidXML 是一个轻量级、高性能的 XML 解析库,以单头文件形式提供(rapidxml.hpp 及辅助头文件),适合在 C++ 中解析中小型 XML 文档。
- 获取 RapidXML:从 官方网站 下载头文件(rapidxml.hpp、rapidxml_utils.hpp、rapidxml_print.hpp 等),放入项目目录。
- 使用方式:在代码中直接包含头文件
#include "rapidxml.hpp"
#include "rapidxml_utils.hpp" // 提供文件读取工具
#include "rapidxml_print.hpp" // 提供节点打印功能(可选)
2.解析 XML 文件的核心步骤
- 加载 XML 内容:将文件内容读入内存(字符串)。
- 解析文档:使用 rapidxml::xml_document 解析字符串,生成节点树。
- 获取根节点:从解析后的文档中获取根节点。
- 遍历节点:通过节点的 first_child()、next_sibling() 等方法遍历子节点和属性。
3.解析XML文件
假设存在 data.xml 文件 :
<?xml version="1.0" encoding="UTF-8"?>
<REFCTRL Ver="1.0.0"><para><node name="年龄" value="22" /></para><point><node name="性别" main="1" /><node name="体重" main="50"><sub_node name="小马" main="23" /><sub_node name="小龟" main="34" /></node></point>
</REFCTRL>
解析代码如下:
#include <iostream>
#include <string>
#include "rapidxml.hpp"
#include "rapidxml_utils.hpp" // 用于快速读取文件using namespace rapidxml;
using namespace std;int main()
{ file<> xmlFile("data.xml"); // 1. 读取 XML 文件到内存.自动读取文件内容,析构时释放内存xml_document<> doc; // 2. 创建文档对象并解析 XML 内容doc.parse<0>(xmlFile.data()); // 解析XML内容xml_node<>* root = doc.first_node("REFCTRL"); // 3. 获取根节点(XML 文档必须有唯一根节点)xml_attribute<>* verAttr = root->first_attribute("Ver"); // 4. 解析根节点的属性(如 Ver="1.0.0")// 5. 遍历根节点的子节点(para 和 point)for (xml_node<>* child = root->first_node(); child; child = child->next_sibling()) {// 6. 遍历子节点的子节点(如 para 下的 node)for (xml_node<>* grandChild = child->first_node(); grandChild; grandChild = grandChild->next_sibling()) {// 7. 解析孙节点的属性(如 name、value、main)xml_attribute<>* nameAttr = grandChild->first_attribute("name");xml_attribute<>* valueAttr = grandChild->first_attribute("value");xml_attribute<>* mainAttr = grandChild->first_attribute("main");// 8. 处理孙节点的子节点(如“体重”node 下的 sub_node)for (xml_node<>* greatGrandChild = grandChild->first_node(); greatGrandChild; greatGrandChild = greatGrandChild->next_sibling()) {xml_attribute<>* subNameAttr = greatGrandChild->first_attribute("name");xml_attribute<>* subMainAttr = greatGrandChild->first_attribute("main");}}}return 0;
}