-1

我有这个 XML 文件

<?xml version="1.0" encoding="UTF-8"?>
<scene>
  <file>sphere.d3</file>
</scene>

这个函数应该将所有“文件”元素放入一个向量中

vector<string> loadXML(string file){

    vector<string> files;

    XMLDocument xml_doc;
    xml_doc.LoadFile(file);

    if(xml_doc.ErrorID() != 0) {
        cout << xml_doc.ErrorName() << endl;
        return files;
    }

    XMLNode* scene = xml_doc.FirstChild();
    if(scene == nullptr){
        cout << "No Root Found\n" << endl;
        return files;
    }

    string temp;

    XMLElement* shape = scene -> FirstChildElement("file"); //error getting this element
    if(shape == nullptr){
        cout << "Error Reading XML file\n";
        return files;
    }

    temp = shape -> GetText();
    files.push_back(temp);

    while(shape != nullptr){
        shape = shape -> NextSiblingElement("file");
        if(shape == nullptr){
            cout << "Error Reading XML file";
            return files;
        }
        temp = shape -> GetText();
        files.push_back(temp);
    }

    return files;

}

但是,当尝试从根目录获取第一个“文件”元素时,它给了我一个空 ptr。任何帮助将不胜感激。谢谢

4

1 回答 1

0

请考虑这样做:

tinyxml2::XMLElement* pScene = xml_doc.FirstChildElement("Scene");
if (pScene != nullptr)
{
    //...
}

这就是我从 XML 数据文件中读取第一个元素并且没有遇到问题的方式。

于 2020-03-14T20:32:11.443 回答