0

所以我已经做了好几天了,我不知道为什么会抛出 BAD_ACCESS 错误。有时有效,有时无效。

void xmlParser::parseXML(string file){

tinyxml2::XMLDocument doc;
if(!doc.LoadFile(file.c_str()))
{
    cout << "ERROR: TINYXML2 FAILED TO LOAD" << endl;
}
//XML FILE LAYOUT:
//<item>
//    <type id="laserWeapon" name="Laser Rifle">
//    <tooltip>
//    <stats>
//</item>

//error seems to occur on this line
tinyxml2::XMLElement* elementType = doc.FirstChildElement("item")->FirstChildElement("type");

string id = elementType->Attribute("id");
string name = elementType->Attribute("name");
cout << "id: " << id << endl;
cout << "name: " << name << endl;
}   

我使用 xmlparser.parseXML(xmlparser.path+"laserRifle.xml"); 加载文件。我应该将其解析为字符串,还是我忽略了一些 null ptr?我试图做一个'if nullptr'子句,但它仍然是一个错误而不是跳过它。

关于做什么的任何建议?我完全迷失了。

4

1 回答 1

0
// item element can be missed and you'll get bad access. Do not chain your calls that way

tinyxml2::XMLElement* elementType = doc.FirstChildElement("item")->FirstChildElement("type");

// element type can be missed, as well as attributes id and name
string id = elementType->Attribute("id");
string name = elementType->Attribute("name");
cout << "id: " << id << endl;
cout << "name: " << name << endl;
}   

仔细检查每个元素和属性。不要链接调用,因为每个调用都可以返回 null。如果您检查所有 nullptr 案例,您会发现错误

于 2014-06-15T09:17:31.863 回答