在C++中处理XML:选择用于解析和创建文档的库
XML(可扩展标记语言)仍然是存储和传输结构化数据的关键格式之一。C++没有内置的XML支持(除了已过时的MSXML),因此开发者使用第三方库。在本文中,我们将介绍三种最流行的轻量级库:pugixml、TinyXML-2和RapidXML。它们都不依赖外部库,支持UTF-8,并且适用于嵌入式系统。
1. pugixml — 通用选择
pugixml 是“轻量级”解决方案中速度最快、功能最丰富的库。它支持XPath、流式处理以及类似STL的便捷API。
安装:只需将 pugixml.hpp 和 pugixml.cpp 复制到项目中即可。
示例:解析和读取XML
#include "pugixml.hpp"#include <iostream>
int main() { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file("config.xml");
if (!result) { std::cerr << "错误:" << result.description() << std::endl; return 1; }
// 获取根元素 pugi::xml_node root = doc.child("configuration");
// 遍历所有 <parameter> 元素 for (pugi::xml_node param : root.children("parameter")) { std::string name = param.attribute("name").value(); std::string value = param.child_value("value"); std::cout << name << " = " << value << std::endl; }
return 0;}创建XML文档
pugi::xml_document doc;pugi::xml_node root = doc.append_child("root");root.append_attribute("version") = "1.0";
pugi::xml_node item = root.append_child("item");item.append_attribute("id") = 1;item.append_child("name").text().set("示例");item.append_child("price").text().set(99.99);
doc.save_file("output.xml");特点:
- 支持XPath 1.0,用于复杂查询。
- 支持UTF-8/16/32编码。
- 针对大文件的“惰性”解析模式。
2. TinyXML-2 — 简单与可靠
TinyXML-2 是经典TinyXML的继承者,针对内存进行了优化。非常适合不需要XPath的简单项目。
安装:两个文件:tinyxml2.h 和 tinyxml2.cpp。
示例:读取属性
#include "tinyxml2.h"#include <iostream>
int main() { tinyxml2::XMLDocument doc; tinyxml2::XMLError err = doc.LoadFile("data.xml");
if (err != tinyxml2::XML_SUCCESS) { std::cerr << "加载错误:" << doc.ErrorStr() << std::endl; return 1; }
tinyxml2::XMLElement* element = doc.FirstChildElement("book"); if (element) { const char* title = element->Attribute("title"); int pages = element->IntAttribute("pages"); std::cout << "书名:" << title << ",页数:" << pages << std::endl; }
return 0;}创建XML
tinyxml2::XMLDocument doc;tinyxml2::XMLDeclaration* decl = doc.NewDeclaration();doc.InsertFirstChild(decl);
tinyxml2::XMLElement* root = doc.NewElement("catalog");doc.InsertEndChild(root);
tinyxml2::XMLElement* product = doc.NewElement("product");product->SetAttribute("id", 101);product->SetText("笔记本电脑");root->InsertEndChild(product);
doc.SaveFile("catalog.xml");优点:
- 内存消耗极低(不复制字符串)。
- 简单直观的API。
- 支持XML注释和CDATA。