0

I've recently started using tinyXML. The problem is when I run my program to read through xml, it returns back an access violation. A common line is:

doc.FirstChildElement("Map")->FirstChildElement("Width")->GetText()

With the visual studio debugger, I determined that it is returning null for the 'Map', and then is using a null reference to call functions.

Here is the first lines of code, and the xml

XMLDocument doc;
    doc.LoadFile(path.c_str());

    int width = atoi(doc.FirstChildElement("Map")->FirstChildElement("Width")->GetText());

XML:

<?xml version="1.0"?>
 <Master>
 <Map>
    <Width>5</Width>
    <Height>5</Height>
    <Layers>1</Layers>
    <Tiles>
        <Tile>
            <Id>1</Id>
            <Path>data/tiles/dirt-base.png</Path>
        </Tile>
    </Tiles>
    <Data>
        <DataLayer>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</DataLayer>
    </Data>
 </Map>
 </Master>

IT is important to note, I originally did not have the root tag, but added it when it didn't work, adding it still didn't help though. Any help would be appreciated

will
  • 1,397
  • 5
  • 23
  • 44

3 Answers3

3

change

int width = atoi(doc.FirstChildElement("Map")->FirstChildElement("Width")->GetText());

to

int width = atoi(doc.FirstChildElement("Master")->FirstChildElement("Map")->FirstChildElement("Width")->GetText());

it's working on my pc use the newest tinyxml.

according to TinyXml Documentation

you should first check the LoadFile return

if (!_doc.LoadFile(filename))
{
    printf("load file=[%s] failed\n", filename);
    return -1;
}

then check the element exist to avoid access violation.

it is easier to use TiXmlHandle to check the element.

TiXmlHandle docHandle(&doc);
TiXmlElement* child = docHandle.FirstChild("Map").FirstChild("Width").ToElement();
if (child)
{
    // do something useful
Howard Wo
  • 31
  • 2
1

Like you said in the comments of your question, error code 3 is file not found You've more than likely sorted this out, but a common cause of this is simply getting the backslashes in the path the wrong way around.

Just had this exact problem myself. Having done a fair bit of web development, an environment where the slashes are in different directions within the same project because of the different scripting/ markup/ server-side / client-side funk going on (and where you sometimes need to reverse the direction of half your slashes when publishing!), this crops up a lot. Still had me stumped for a good hour.

Sticking this possible solution up late for for reference's sake - this is the most prominent Google result on TinyXML and this problem.

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
Stuart
  • 69
  • 1
  • 4
0

Looks to me like one of those TinyXML functions you're calling is returning an invalid pointer. Try to check the result of each call separately and you'll be able to pin down the problem.