Search code examples
c++xmltinyxml2

Get integers and floats from xml


I'm using tinyxml2 and I know how to get strings of attributes, but I want to also get integers, floats and booleans too. So, I have this code:

#include <iostream>
#include <fstream>
#include <tinyxml2.h>
using namespace std;
using namespace tinyxml2;

int main()
{
    XMLDocument doc;
    doc.LoadFile("sample.xml");

    XMLElement *titleElement = doc.FirstChildElement("specimen");

    int f = -1;
    if (!titleElement->QueryIntAttribute("age", &f))
        cerr << "Unable to get value!" << endl;

    cout << f << endl;

    return 0;
}

And sample.xml being:

<?xml version=1.0?>

<specimen>
    <animal>
        Dog
    </animal>
    <age>
        12
    </age>
</specimen>

Don't worry, the xml file is just a fake sample, nothing real!

Anyway, I am still not able to get the integer value that's within the attribute 'age'. If this doesn't work, then how should I use tinyxml2 to get ints and floats from an xml document?


Solution

  • I believe, that the correct method to use is QueryIntText not QueryIntAttribute - you are trying to get the value of an XML node, not attribute.

    Consult the documentation for further details and usage:http://www.grinninglizard.com/tinyxml2docs/classtinyxml2_1_1_x_m_l_element.html#a8b92c729346aa8ea9acd59ed3e9f2378