TINYXML2 Introduction
TINYXML2 is a lightweight XML parser written in C + + that is open source and is used in a number of open source game engines. The source code is hosted on the GitHub.
Source Address: HTTPS://GITHUB.COM/LEETHOMASON/TINYXML2
TINYXML2 is very simple to use, download the source code after the need to compile into a Lib file, directly to Tinyxml2.h and tinyxml2.cpp two files to add to your own project can be. TINYXML2 Use
We now have a persons.xml file with some staff information, which reads as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<persons>
<person name= "John" >
<sex> Male </sex>
<age>30</age>
</person>
<person name= "Flower" >
<sex> Female </sex>
<age>20</age>
</person>
</persons>
Now we use the TINYXML2 library to traverse the XML file and get the full information of the person whose name is "Flower."
The code is as follows:
#include "stdafx.h" #include <string> #include <iostream> #include "tinyxml2.h" #define String std::string US
ing namespace tinyxml2;
using namespace Std;
int _tmain (int argc, _tchar* argv[]) {/* <?xml version= "1.0" encoding= "UTF-8"?> <persons> <person name= "John" > <sex> male </sex> <age>30</age> </PERSON&G
T <person name= "Flowers" > <sex> women </sex> <age>20</age> </person>
;
</persons>///by traversing the output name "flower" personal information xmldocument* doc = new XmlDocument (); if (Doc->loadfile ("Persons.xml")!= xml_no_error) {cout<< "read file error!"
<<endl;
return-1;
//Get the root node, that is, the persons node xmlelement* root = Doc->rootelement ();
xmlelement* person = root->firstchildelement ("person"); while (person) {//Get person's Name property Const XMLATTRIBUte * nameattr = Person->firstattribute ();
String pername = Nameattr->value (); if (Pername = "Flowers") {cout<<nameattr->name () << ":" <<nameattr->value () <<
Endl
Traversing other child nodes of person XmlElement * perattr = Person->firstchildelement (); while (perattr) {cout<<perattr->name () << ":" <<perattr->gettext () <&
Lt;endl;
Perattr = Perattr->nextsiblingelement ();
person = person->nextsiblingelement ();
} Delete doc;
System ("pause");
}
TINYXML2 uses the DOM (Document Object model) to process XML files, and each element in an XML file has a corresponding class.
Doc->loadfile ("Persons.xml")
The object of the XmlDocument class represents an instance of an XML document and calls the LoadFile method to bind to the XML file.
xmlelement* root = Doc->rootelement ();
We get the root node (only one root node of the XML file) through the rootelement of the XmlDocument class, and get the first child node of the element named person by root->firstchildelement ("person"). This node calls the XmlElement class Nextsiblingelement () method to iterate through the loop. Run effect
We can see the information we need to print out.