SoFunction
Updated on 2025-03-05

tinyxml commonly used C++ XML parser is very excellent


#include <iostream>
#include ""
#include ""
#include <string>
#include <>
#include <>
using namespace std;
CString GetAppPath()
{//Get the application root directory
TCHAR modulePath[MAX_PATH];
GetModuleFileName(NULL, modulePath, MAX_PATH);
CString strModulePath(modulePath);
strModulePath = ((_T('\\')));
return strModulePath;
}
bool CreateXmlFile(string& szFileName)
{//Create an xml file, szFilePath is the path to save the file. If the creation is successful, return true, otherwise false
try
{
//Create an XML document object.
TiXmlDocument *myDocument = new TiXmlDocument();
//Create a root element and connect.
TiXmlElement *RootElement = new TiXmlElement("Persons");
myDocument->LinkEndChild(RootElement);
//Create a Person element and connect.
TiXmlElement *PersonElement = new TiXmlElement("Person");
RootElement->LinkEndChild(PersonElement);
//Set the properties of the Person element.
PersonElement->SetAttribute("ID", "1");
//Create name element, age element and connect.
TiXmlElement *NameElement = new TiXmlElement("name");
TiXmlElement *AgeElement = new TiXmlElement("age");
PersonElement->LinkEndChild(NameElement);
PersonElement->LinkEndChild(AgeElement);
//Set the contents of the name element and the age element and connect it.
TiXmlText *NameContent = new TiXmlText("Zhou Xingxing");
TiXmlText *AgeContent = new TiXmlText("22");
NameElement->LinkEndChild(NameContent);
AgeElement->LinkEndChild(AgeContent);
CString appPath = GetAppPath();
string seperator = "\\";
string fullPath = (0) +seperator+szFileName;
myDocument->SaveFile(fullPath.c_str());//Save to file
}
catch (string& e)
{
return false;
}
return true;
}
bool ReadXmlFile(string& szFileName)
{//Read the Xml file and traverse it
try
{
CString appPath = GetAppPath();
string seperator = "\\";
string fullPath = (0) +seperator+szFileName;
//Create an XML document object.
TiXmlDocument *myDocument = new TiXmlDocument(fullPath.c_str());
myDocument->LoadFile();
//Get the root element, i.e. Persons.
TiXmlElement *RootElement = myDocument->RootElement();
//Output the root element name, that is, output Persons.
cout << RootElement->Value() << endl;
//Get the first Person node.
TiXmlElement *FirstPerson = RootElement->FirstChildElement();
//Get the name node and age node and ID attributes of the first Person.
TiXmlElement *NameElement = FirstPerson->FirstChildElement();
TiXmlElement *AgeElement = NameElement->NextSiblingElement();
TiXmlAttribute *IDAttribute = FirstPerson->FirstAttribute();
//Output the name content of the first Person, that is, Zhou Xingxing; age content, that is, ID attribute, that is.
cout << NameElement->FirstChild()->Value() << endl;
cout << AgeElement->FirstChild()->Value() << endl;
cout << IDAttribute->Value()<< endl;
}
catch (string& e)
{
return false;
}
return true;
}
int main()
{
string fileName = "";
CreateXmlFile(fileName);
ReadXmlFile(fileName);
}