C++ XML庫用法詳解
更新時間:2025年03月26日 11:02:05 作者:少年丶趁年輕
TinyXML-2是C++中一個輕量級、易于使用的XML解析庫,支持XML的讀取和寫入,內(nèi)存占用小,適合嵌入式系統(tǒng),本文給大家介紹C++ XML庫用法,感興趣的朋友一起看看吧
在C++中,處理XML文件的讀寫操作可以通過多種庫來實現(xiàn)。以下是幾個常用且簡潔的庫:
1. ?TinyXML-2
- ?簡介: TinyXML-2 是一個輕量級的C++ XML解析庫,易于使用且性能良好。
- ?特點:
- 簡單易用,API直觀。
- 內(nèi)存占用小,適合嵌入式系統(tǒng)。
- 支持XML文件的讀取和寫入。
- ?安裝: 只需包含頭文件和源文件即可。
TinyXML-2 和 ?pugixml 是最常用的XML處理庫,適合大多數(shù)場景。
#include "xml_lib/tinyxml2.h" #include <iostream> using namespace tinyxml2; int main() { // 創(chuàng)建 XML 文檔對象 XMLDocument doc; // 讀取 XML 文件 if (doc.LoadFile("demo.xml") != XML_SUCCESS) { std::cerr << "Failed to load XML file!" << std::endl; return 1; } // 獲取根節(jié)點 XMLElement* root = doc.FirstChildElement("RegisterDescription"); if (!root) { std::cerr << "No root element found!" << std::endl; return 1; } // 讀取子節(jié)點內(nèi)容 // XMLElement* element = root->FirstChildElement("Name=public_system_status"); // if (element) { // XMLElement* element2 = element->FirstChildElement("DisplayName"); // std::cout << "Element2 text: " << element2->GetText() << std::endl; // } /* 遍歷節(jié)點信息 */ for (XMLElement* child = root->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) { // 檢查節(jié)點名稱是否為 "Integer" if (strcmp(child->Name(), "Integer") == 0) { // 檢查屬性 "Name" 和 "NameSpace" 是否符合條件 const char* name = child->Attribute("Name"); const char* nameSpace = child->Attribute("NameSpace"); if (name && nameSpace && strcmp(name, "public_reserved_0x0008") == 0 && strcmp(nameSpace, "Custom") == 0) { // 找到目標(biāo)節(jié)點 //std::cout << "Found target node: " << child->Name() << std::endl; std::cout << "Found target node: " << child->FirstChildElement("pValue")->GetText() << std::endl; // 獲取節(jié)點的文本內(nèi)容(如果有) const char* text = child->GetText(); if (text) { std::cout << "Node text: " << text << std::endl; } // 可以在這里處理目標(biāo)節(jié)點 break; // 找到后退出循環(huán) } } } // 修改或添加新節(jié)點 XMLElement* newElement = doc.NewElement("newElement"); newElement->SetText("LiuMing"); root->InsertEndChild(newElement); // 保存修改后的 XML 文件 if (doc.SaveFile("gigevdevice.xml") != XML_SUCCESS) { std::cerr << "Failed to save XML file!" << std::endl; return 1; } std::cout << "XML file updated successfully!" << std::endl; return 0; }
到此這篇關(guān)于C++ XML庫用法詳解的文章就介紹到這了,更多相關(guān)c++ XML庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ std::initializer_list 實現(xiàn)原理解析及遇到問題
這篇文章主要介紹了C++ std::initializer_list 實現(xiàn)原理勘誤,本文通過源碼解析給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02一文詳解C++中的轉(zhuǎn)換構(gòu)造函數(shù)
在 C/C++ 中,不同的數(shù)據(jù)類型之間可以相互轉(zhuǎn)換,無需用戶指明如何轉(zhuǎn)換的稱為自動類型轉(zhuǎn)換(隱式類型轉(zhuǎn)換),需要用戶顯式地指明如何轉(zhuǎn)換的稱為強(qiáng)制類型轉(zhuǎn)換,本文就給大家詳細(xì)介紹一下C++的轉(zhuǎn)換構(gòu)造函數(shù),需要的朋友可以參考下2023-09-09C++基于隨機(jī)數(shù)實現(xiàn)福彩雙色球的方法示例
這篇文章主要介紹了C++基于隨機(jī)數(shù)實現(xiàn)福彩雙色球的方法,結(jié)合完整實例形式分析了C++隨機(jī)數(shù)算法的實現(xiàn)與使用技巧,需要的朋友可以參考下2017-06-06