Using TinyXML-2 to parse XML in C++
Table of contents
Introduction
TinyXML-2 is a lightweight XML parser to build Document Object Model (DOM) that is easily readable and modifiable. The XML data is parsed into C++ objects to write to an output stream or disk.
Getting Started
TinyXML-2 is simple and easy to learn. You just need to add one header file and one cpp file named as tinyxml2.h and tinyxml2.cpp respectively to your C++ project. For licensing and more information click here.
Sample XML
XML stands for eXtensible Markup Language and is similar to HTML but without any pre-defined tags. It is one of the most widely used format for sharing structured information. Below is a sample xml and we'll be using tinyxml2 to parse it.
<?xml version="1.0"?>
<catalog>
<book id="1101">
<name>XML Developer's Guide</name>
<author>Gambardella, Matthew</author>
<genre>Computer</genre>
<cost>395</cost>
<publish_date>2000-10-01</publish_date>
<descript>An in-depth look at creating applications
with XML.</descript>
</book>
<book id="9112">
<name>Midnight Rain</name>
<author>Ralls, Kim</author>
<genre>Fantasy</genre>
<cost>739</cost>
<publish_date>2000-12-16</publish_date>
<descript>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</descript>
</book>
</catalog>
C++ Program
Let's write a simple C++ program to retrieve book's name and cost against the respective tags.
#include <iostream>
#include <string>
#include tinyxml2.h
using namespace tinyxml2;
using namespace std;
//function to parse XML string
void parseXML(string& src) {
XMLDocument doc;
doc.Parse(src.c_str());
const char* bookName;
const char* bookCost;
XMLElement* rootElement = doc.RootElement(); //<catalog>
XMLElement* child = rootElement -> FirstChildElement("book"); //<book>
while(child) {
XMLElement* name = child -> FirstChildElement("name"); //<name>
bookName = name -> GetText();
//print bookName if required
XMLElement* cost = child -> FirstChildElement("cost"); //<cost>
bookCost = cost -> GetText();
}
}
Hope this article helps you to parse XML in C++ specially in use cases such as http/https requests where server response is in XML format.
Subscribe to my newsletter
Read articles from Juhilee Nazare directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Juhilee Nazare
Juhilee Nazare
I've 3.5+ years of experience in software development and willing to share my knowledge while working on real-time IT solutions.