Saturday, April 2, 2016

Loading XML data with C++

I've been writing code that reads/writes data to/from text files since ~1993. When I am coding in C++, I still use the techniques I learned by trial and error 20+ years ago. As a result, I use a lot of fprintf and fscanf statements, and my text files end up with custom formats that are hard for others to use.

Recently, I've been thinking of moving towards XML. I think this will be fairly easy for code that I write in MATLAB but I wasn't sure how difficult it would be for C++. Today, I've learned that I have a chance!

Some quick googling pushed me towards TinyXML-2. It's well-documented and it seems to be actively supported. Another big advantage is that I only need to add 2 files (tinyxml2.h, tinyxml2.cpp) to my existing code.

As usual, I had to play around for a few minutes to get anything to work, but it was easier than I thought given my limited experience. For example, this C++

// Test
tinyxml2::XMLDocument doc;
XMLElement* a;
const char* b;


a = doc.FirstChildElement("MotilSim_model")->
b = a->GetText();
printf("eta_o: %s\n",b);



from the XML file that looks like this

<?xml version="1.0" encoding="windows-1252"?>


<g>10 1</g>

No comments:

Post a Comment