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;

doc.LoadFile("C:\\temp\\test_xml.xml");

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

return(0);


produces









from the XML file that looks like this

<?xml version="1.0" encoding="windows-1252"?>
<MotilSim_model>
<code_data>
<ver>1.1</ver>
</code_data>
<field_data>
<random_seed>3</random_seed>
<no_of_time_steps>20</no_of_time_steps>
</field_data>

<thin_data>
<rest_length>5.5e-9</rest_length>
<k_a>0.02</k_a>
<eta_o>6e-11</eta_o>
<k_torque>1e-14</k_torque>
<m>0.7e-19</m>
<alignment_factor>20</alignment_factor>
</thin_data>

<cb_data>
<k_cb>0.001</k_cb>
<x_ps>10e-9</x_ps>
<f>0</f>
<g>10 1</g>
</cb_data>
</MotilSim_model>

No comments:

Post a Comment