A simple and functional tool to read your games' tilemaps.
We have already published about Expat XML which is also a alternative for parsing XML.
However, TinyXML2 is simpler and just as efficient as Expat .
TinyXML2 parses an XML document and builds from it a Document Object Model (DOM) that can be read, modified and saved.
TinyXML2 is an improvement of TinyXML 1, but TinyXML2’s parser implementation is more suitable for use in games. It uses less memory, is faster, and uses far fewer memory allocations.
Installing the library in your project
I forked the original project so that the repository has fewer files and takes less time for you to implement, because the library itself is only 2 files: the header(tinyxml2.hpp) and the source(tinyxml2.cpp ).
In the original version the header is with .h extension I renamed it to tinyxml2.hpp, ie .hpp extension.
To implement, use Git to clone and use the tinyxml2.hpp and tinyxml2.cpp files for your project.
In the examples below we will simulate a blog instead of a game which is easier to understand according to articles.
1. Parsing an XML with only one tag
First example of an XML file:
first.xml
File with the main() function with the code: first.cpp
Compile: g++ first.cpp tinyxml2/tinyxml2.cpp and run: ./a.out
Possible and probable output:
Note that the root element(*p_root_element) is the <title> .
2. Parsing an XML with two hierarchical tags
The root element is now the <article> tag
second.xml
Consequently we need to create a pointer for the root element and inform the tag
second.cpp
Possible and probable output:
If your article has multiple elements, for example:
Your code would be like this:
If you want to make your code more LIKE A BOSS!, use a vector:
Possible and probable output:
If you use std::string in your vector, convert the elems[i] to c_str() like this: elems[i].c_str().
From here we will use this LIKE A BOSS! syntax for the next examples!
3. Selecting multiple articles
The root element is now the <blog>:
third.xml
And the code: vim third.cpp
Note that the *p_article pointer gets the first element from root and the *ptr gets it. To jump to the next article, we use: p_article = p_article->NextSiblingElement("article"); inside and at the end of the while loop. The ternary condition was just to separate the articles.
Possible and probable output:
4. Filtering the data inside a sub root element
Imagine if there was one more <data> element after root to make a more expressive hierarchy, for example:
vim fourth.xml
In the code we would have two loops while and *p_article would now get the FirstChildElement() of *p_data :
vim fourth.cpp
Possible and probable output:
It is still possible to change contents, get tag names, line numbers and other features. For complete documentation see this link .