In this article, we are going to discuss how to parse XML in C++ programming language. We will see several working examples to understand the XML parsing mechanism in C++.
What is XML?
XML is a markup language and is mainly used for storing and transferring data in an organized way. XML stands for eXtensible Markup Language. It is very similar to HTML. The XML is completely focused on storing and transferring the data, whereas the HTML is used for displaying the data on the browser.
A Sample XML File/XML Syntax
Here is a sample XML file:
Unlike HTML, It is a tag-oriented markup language, and we can define our own tag in an XML file. In the above example, we have several user-defined tags such as “<Employee>”. Every tag will have the corresponding ending tag. “</Employee>” is the ending tag for “<Employee>”. We can define as many user-defined tags as we want to organize the data.
Parsing Libraries in C++:
There are various libraries to parse XML data in most of the high-level programming languages. C++ is not an exception. Here are the most popular C++ libraries to parse XML data:
As the name suggests, the RapidXML is mainly focused on speed, and it is a DOM style parsing library. PugiXML supports Unicode conversion. You may want to use PugiXML if you want to convert UTF-16 doc to UTF-8. TinyXML is a bare-minimum version to parse XML data and not that fast as compared to the previous two. If you want to just get the job done and don’t care about the speed, you can choose TinyXML.
Now, we have a basic understanding of XML and XML parsing libraries in C++. Let’s now look at a couple of examples to parse xml file in C++:
- Example-1: Parse XML in C++ using RapidXML
- Example-2: Parse XML in C++ using PugiXML
- Example-3: Parse XML in C++ using TinyXML
In each of these examples, we will use the respective libraries to parse a sample XML file.
Example-1: Parse XML in C++ using RapidXML
In this example program, we will demonstrate how to parse xml using RapidXML library in C++. Here is the input XML file (sample.xml):
Our goal here is to parse the above XML file using C++. Here is the C++ program to parse XML data using RapidXML. You can download the RapidXML library from Here.
using namespace std;
using namespace rapidxml;
xml_node<> * root_node = NULL;
cout << “nParsing my students data (sample.xml)…..” << endl;
// Read the sample.xml file
ifstream theFile (“sample.xml”);
vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());