In C++, the read and write operations of XML files can be implemented through various libraries. Here are a few commonly used and concise libraries:
1. TinyXML-2
- Introduction: TinyXML-2 is a lightweight C++ XML parsing library that is easy to use and has good performance.
- Features:
- Simple and easy to use, and the API is intuitive.
- Small memory footprint, suitable for embedded systems.
- Supports reading and writing of XML files.
- Install: Just include the header file and the source file.
TinyXML-2andpugixmlIt is the most commonly used XML processing library and is suitable for most scenarios.
#include "xml_lib/" #include <iostream> using namespace tinyxml2; int main() { // Create XML document object XMLDocument doc; // Read XML files if (("") != XML_SUCCESS) { std::cerr << "Failed to load XML file!" << std::endl; return 1; } // Get the root node XMLElement* root = ("RegisterDescription"); if (!root) { std::cerr << "No root element found!" << std::endl; return 1; } // Read child node content // XMLElement* element = root->FirstChildElement("Name=public_system_status"); // if (element) { // XMLElement* element2 = element->FirstChildElement("DisplayName"); // std::cout << "Element2 text: " << element2->GetText() << std::endl; // } /* traversal node information */ for (XMLElement* child = root->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) { // Check whether the node name is "Integer" if (strcmp(child->Name(), "Integer") == 0) { // Check whether the properties "Name" and "NameSpace" meet the criteria 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) { // Find the target node //std::cout << "Found target node: " << child->Name() << std::endl; std::cout << "Found target node: " << child->FirstChildElement("pValue")->GetText() << std::endl; // Get the text content of the node (if any) const char* text = child->GetText(); if (text) { std::cout << "Node text: " << text << std::endl; } // The target node can be processed here break; // Exit the loop after finding it } } } // Modify or add new nodes XMLElement* newElement = ("newElement"); newElement->SetText("LiuMing"); root->InsertEndChild(newElement); // Save the modified XML file if (("") != XML_SUCCESS) { std::cerr << "Failed to save XML file!" << std::endl; return 1; } std::cout << "XML file updated successfully!" << std::endl; return 0; }
This is the end of this article about the detailed explanation of the usage of C++ XML library. For more related content of C++ XML library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!