I was searching for a easy,fast and small XML Parser for my project when I came across TinyXML2. I tried it and found that its indeed an easy and clean little parser which can cater to my need excellently.
Now lets see how it works.
You can get it from : https://github.com/leethomason/tinyxml2
Just download it and build the files using the solution available in the folder. Then you will get Object file(tinyxml.obj) in “tinyxml2-master\tinyxml2\Win32\Release” or “tinyxml2-master\tinyxml2\Win32\Debug” depends up on which configuration you built.
You will have to link the object file in your project settings or else you will get “Unresolved external symbol errors”.
Include “tinyxml2.h” in your C++ file.
Now we are ready to Tackle XMLs.
Load and Parse XML File
Create a XMLDocument Object and call LoadFile() function. Give the file path as its parameter.
Parse XML formatted string
If you have a string which contains an XML, You can parse that using XMLDocument’s parse function.
//Parse the xml sxml
int rslt = dxml.Parse(sxml.c_str());
Getting root node
You can get the root node by calling FirstChild function of XMLDocument. It will return a pointer to the XMLNode class
XMLNode *rootnode = dxml.FirstChild();
Iterating Sibling Nodes
Then to iterate the nodes in the same level call NextSibling() function of XMLNode
XMLNode SiblingNode = rootnode ->NextSibling();
Getting Child Node
To get down to the child level nodes of current node call FirstChild() function of XMLNode
ChildNode = SiblingNode ->FirstChild();
Getting Data from Nodes
To get data from nodes we need to get the xml element from the Node. XMLNode class provides ToElement() function for this operation.
XMLElement *ChildElmt = ChildNode->ToElement();
Then we can get the Tag name of the Node using Name() function of XMLElement class.
string strTagName = ChildElmt ->Name();
We can get the values of the attributes of elements using the Attribute() function by giving the attribute name as parameter.
string strAttr = ChildElmt ->Attribute("YourAttributeName");
I am using tinyxml for some time now. And I must say I love its simplicity..