XML is a commonly used data exchange format and is widely used in networks, databases, configuration files and other fields. In C, XML processing can be completed through third-party libraries, such as TinyXML, RapidXML, Boost.PropertyTree, etc. This article will introduce techniques for using the TinyXML library to process XML files.
#include "tinyxml.h" #include <iostream> using namespace std; int main() { TiXmlDocument xmlDocument; if (xmlDocument.LoadFile("example.xml")) { cout << "文件加载成功!" << endl; } else { cout << "文件加载失败,请检查文件路径是否正确。" << endl; } return 0; }
#include "tinyxml.h" #include <iostream> using namespace std; int main() { TiXmlDocument xmlDocument; if (xmlDocument.LoadFile("example.xml")) { TiXmlElement* rootElement = xmlDocument.RootElement(); for (TiXmlElement* element = rootElement->FirstChildElement(); element != nullptr; element = element->NextSiblingElement()) { cout << "元素名称:" << element->Value() << endl; for (TiXmlAttribute* attribute = element->FirstAttribute(); attribute != nullptr; attribute = attribute->Next()) { cout << "属性名称:" << attribute->Name() << ",属性值:" << attribute->Value() << endl; } } } else { cout << "文件加载失败,请检查文件路径是否正确。" << endl; } return 0; }
#include "tinyxml.h" #include <iostream> using namespace std; int main() { TiXmlDocument xmlDocument; if (xmlDocument.LoadFile("example.xml")) { TiXmlElement* element = xmlDocument.RootElement()->FirstChildElement("person")->FirstChildElement("name"); element->SetValue("John Smith"); TiXmlAttribute* attribute = element->FirstAttribute("lang"); attribute->SetValue("en"); xmlDocument.SaveFile("example.xml"); cout << "更新成功!" << endl; } else { cout << "文件加载失败,请检查文件路径是否正确。" << endl; } return 0; }
#include "tinyxml.h" #include <iostream> using namespace std; int main() { TiXmlDocument xmlDocument; TiXmlElement* rootElement = new TiXmlElement("root"); TiXmlElement* personElement = new TiXmlElement("person"); TiXmlElement* nameElement = new TiXmlElement("name"); nameElement->SetValue("Tom"); nameElement->SetAttribute("lang", "en"); personElement->LinkEndChild(nameElement); rootElement->LinkEndChild(personElement); xmlDocument.LinkEndChild(rootElement); xmlDocument.SaveFile("example.xml"); cout << "创建成功!" << endl; return 0; }
In addition to the above operations, the TinyXML library also provides other methods to operate XML files, such as deleting nodes, querying nodes, etc. Using the TinyXML library can make XML processing in C easy and simple, and improve development efficiency.
The above is the detailed content of XML processing skills in C++. For more information, please follow other related articles on the PHP Chinese website!