TinyXML2 Parser Tutorial using C++ (Read – Write)

C++, without any doubt, is the most popular programming language that can be found literally everywhere. since its birthdate in 1985, C++ has been the base language for learners, engineers, scientists, and researchers.

In some instances, an application written in C++ may require saving and retrieve data that is located in an XML file. There are a few options available here. First, you can create your own XML parse, which is not a bad idea if you have the time and expertise, or simply use an XML parse, such as TinyXML2, without much work other than getting to know how this parser works.

More like this:

In this tutorial, I will briefly introduce the usage of C++ with TinyXML, an XML parse that was created by Lee Thomason.


C++ and TinyXML2 usage

To get started, download the TinyXML library from GitHub, then add it to your solution.

Now add the TinyXML nameSpace to your cpp file

using namespace tinyxml2;

For the purpose of this tutorial, I have created a simple XML file that contains bank accounts. The file initially has two accounts, as shown below

<file>
    <Accounts>
        <Account>
            <AccountNo>1</AccountNo>
            <type>Saving</type>
            <customer>John Doe</customer>
            <balance>399.88</balance>
            <openDate>01/01/2017</openDate>
        </Account>
 
        <Account>
            <AccountNo>94</AccountNo>
            <type>Checking</type>
            <customer>Fredy</customer>
            <balance>525</balance>
            <openDate>03/01/2020</openDate>
        </Account>
    </Accounts>
  
</file>

Read from XML file using TinyXML2

Let’s read the data from the XML file and display it on the console. The file above contains “file”, “Accounts”, and “Account” nodes. So we will have to get to the “Accounts” node, then get its children, which are in the “Account” node.

Now let’s get to the code. I added the sets function for a better layout.

XMLDocument doc;
const char * path = "Your xml path here";
char amountText[100];

// Load the XML file into the Doc instance
doc.LoadFile(path);
// Get root Element
XMLElement * pRootElement = doc.RootElement();

// Print out the Table Header
cout << '|' << setw(7) << "Acc No." << '|' << setw(12) << "Account Type" << '|' << setw(15) << "Customer Name" << '|' << setw(10) << "Balance" << '|' << setw(12) << "Open Date" <<
  endl << endl;

if (NULL != pRootElement) {
  //Get 'Accounts' Child
  XMLElement * pAccounts = pRootElement - > FirstChildElement("Accounts");

  if (NULL != pAccounts) {
    //Get 'Account' Child
    XMLElement * pAccount = pAccounts - > FirstChildElement("Account");

    while (pAccount) {
      // Get 'AccountNo' Child
      XMLElement * pAccountNo = pAccount - > FirstChildElement("AccountNo");

      if (NULL != pAccountNo) {
        //Print out AccountNo
        cout << '|' << setw(7) << pAccountNo - > GetText();

      }

      //Get 'type' Child
      XMLElement * pType = pAccount - > FirstChildElement("type");

      if (NULL != pType) {
        // Print out 'Tyoe'
        cout << '|' << setw(12) << pType - > GetText();
      }

      // Get 'customer' Child
      XMLElement * name = pAccount - > FirstChildElement("customer");

      if (NULL != name) {
        //Print out name
        cout << '|' << setw(15) << name - > GetText();

      }

      // Get 'balance' Child
      XMLElement * balance = pAccount - > FirstChildElement("balance");

      if (NULL != balance) {
        // Convert to *char
        strcpy(amountText, "$");
        strcat(amountText, balance - > GetText());
        //Print out amount
        cout << '|' << setw(10) << amountText << '|';

      }

      // Get 'openDate' Child
      XMLElement * openDate = helper.GetFirstChildElement(pAccount, "openDate");
      if (NULL != openDate) {
        //Print out openDate
        cout << setw(12) << openDate - > GetText() << '|';

      }

      cout << endl;
      cout << "------------------------------------------------------------";
      std::cout << std::endl;
      // Next Account
      pAccount = pAccount - > NextSiblingElement("Account");
    }

    cout << "\n";

  }
}

The output of this code is:


Adding data to an XML file using TinyXML2

Now, let’s add data to our XML file, in this case, a bank account.

A bank account should be instead inside the “Accounts” node, so we have drill down to the “Accounts” node first.

Here is the code to insert data into an XML file using TinyXML2

XMLDocument doc;
const char * path = "your XMl file here";
char accountNumberChar[100];
char typeChar[100];

// Load the XML file into the Doc instance
doc.LoadFile(path);
//Get root Element
XMLElement * pTop = doc.RootElement();

// Get 'Accounts' Child
XMLElement * pAccounts = pTop - > FirstChildElement("Accounts");

//Create new Element
XMLNode * pRoot = doc.NewElement("Account");
//Insert new Element
pAccounts - > InsertEndChild(pRoot);

//Create new Element
XMLElement * pElement = doc.NewElement("AccountNo");
// Set new Element Text
pElement - > SetText("3"); // AccountNo

// Insert new Element
pRoot - > InsertEndChild(pElement);

//Create new Element
pElement = doc.NewElement("type");
// Set new Element Text
pElement - > SetText("checking"); // type

// Insert new Element
pRoot - > InsertEndChild(pElement);

//Create new Element
pElement = doc.NewElement("customer");
// Set new element Text
pElement - > SetText("Craig"); // customer

// Insert new Element
pRoot - > InsertEndChild(pElement);

//Create new Element
pElement = doc.NewElement("balance");
// Set new Element Text
pElement - > SetText("3000"); // balance
// Insert new Element
pRoot - > InsertEndChild(pElement);

//Create new Element
pElement = doc.NewElement("openDate");
// Set new Element Text
pElement - > SetText("06/01/2020"); // openDate

//Insert new Element
pRoot - > InsertEndChild(pElement);

//Save the changes into the XML file
doc.SaveFile(path);

After you run the code above, a new account is added to the list, as shown below:

Happy Coding!!

 

CodingPanel.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.

Leave a Reply

Your email address will not be published. Required fields are marked *