Tinyxml library usage examples

Reading and setting the xml configuration file is the most commonly used operation. It TinyXMLis an open source C++ parsing library for parsing XML, which can be compiled in Windows or Linux. The model of this parsing library parses the XML file and generates it in memory DOM模型, which allows us to traverse the XML tree easily.

TinyXM download address

To use TinyXML, you only need to copy six of the files into the project and you can use them directly. These six files are: tinyxml.h, tinystr.h, tinystr.cpp, tinyxml.cpp, tinyxmlerror.cpp, tinyxmlparser.cpp .

TinyXML includes the following classes:

TiXmlDocument: XML document class, which is generally used to indicate a document object
TiXmlDeclaration;: XML identification class, that is, the relevant information marked in the first line of the XML file;:
TiXmlElementXML node class, this class is used to represent a node
TiXmlText;: XML node class Text information class, which annotates the text information of the XML node class
TiXmlComment;: XML annotation information class, which is used to identify the annotation information of the XML document class;

The inheritance relationship is as follows:
Insert picture description here

Take the following Students.xml as an example to read data:

<Students>
    <Student Name="James" Age = "10">
        <Class>1</Class>
        <Grade>2</Grade>
    </Student>
	<Student Name="Jane" Age = "11">
        <Class>2</Class>
        <Grade>3</Grade>
    </Student>
</Students>

Read the code:

#include <iostream>
#include "tinyxml.h"

#define CheckNullReturnMinusOne(t) if (nullptr == t) { return -1; }

int main()
{
    
    
	const char* path = "Students.xml";
	TiXmlDocument doc(path);

	if (!doc.LoadFile())
	{
    
    
		std::cout << "Load File Failed" << std::endl;
		return -1;
	}

	TiXmlElement* pRoot = doc.RootElement(); CheckNullReturnMinusOne(pRoot);
	for (TiXmlElement* pStudent = pRoot->FirstChildElement(); pStudent != nullptr; pStudent = pStudent->NextSiblingElement())
	{
    
    
		std::cout << "---------------------------------\n";

		// 遍历获取Student节点的所有属性
		for (TiXmlAttribute* pAttribute = pStudent->FirstAttribute(); pAttribute != nullptr; pAttribute = pAttribute->Next())
		{
    
    
			std::cout << pAttribute->Name() << " : " << pAttribute->Value() << std::endl;
		}

		// 获取Student节点的子节点
		for (TiXmlElement* pData = pStudent->FirstChildElement(); pData != nullptr; pData = pData->NextSiblingElement())
		{
    
    
			std::cout << pData->Value() << " : " << pData->GetText() << std::endl;
		}

		std::cout << "----------------------------------\n";
	}
		
	return 0;
}

The output of the program is:

---------------------------------
Name : James
Age : 10
Class : 1
Grade : 2
----------------------------------
---------------------------------
Name : Jane
Age : 11
Class : 2
Grade : 3
----------------------------------

Guess you like

Origin blog.csdn.net/xp178171640/article/details/106212008