2

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?

Poriferous
  • 1,566
  • 4
  • 20
  • 33
  • 1
    What error code is returned? – Alan Stokes Oct 28 '15 at 20:20
  • 1
    Well, age isn't an attribute, is it? I believe an attribute would be within the <> and have `attribute="whatnot"`. – Edward Strange Oct 28 '15 at 20:22
  • From what I can see, the QueryIntAttribute doesn't return the falsely value - shouldn't you rather be checking for the XML_NO_ERROR flag? It might be helpful if you have checked the returned value and added to your question - it may tell us what is wrong – Hipolith Oct 28 '15 at 20:28

3 Answers3

2

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

Hipolith
  • 451
  • 3
  • 14
1

In your if statement you should test for failure like this:

if (titleElement->QueryIntAttribute("age", &f) != TIXML_SUCCESS )
JNK
  • 796
  • 6
  • 12
0

This is what I did to resolve my issue:

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

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

    auto age = doc.FirstChildElement("specimen")
                 ->FirstChildElement("age");

    int x = 0;

    age->QueryIntText(&x);

    cout << x << endl;

    return 0;
}

Suffice it to say I got my xml terminology wrong so I confused attributes with text. At any rate, that's how I got the integer value from the xml doc.

Poriferous
  • 1,566
  • 4
  • 20
  • 33