Почему он неправильно анализирует XML-файл? - PullRequest
0 голосов
/ 04 марта 2019

Я хочу получить из XML-файла имя файла, но похоже, что он не хранит никакой информации о файле.

Структура для хранения имени файла (или файлов позже):

struct Document{
    std::string file1;
    std::string file2;
    std::string file3;
    std::string file4;

}Doc;

Получить элемент из XML-файла:

static std::string getElementText(tinyxml2::XMLElement *_element) {
    std::string value;
    if (_element != NULL) {
        value = _element->GetText();
    }

    return value;
}

Анализ XML-файла:

void parseXml(char* file) {
    tinyxml2::XMLDocument doc;
    doc.LoadFile(file);
    printf("Stuff\n");
    if (doc.ErrorID() == 0) {
        tinyxml2::XMLElement *pRoot;

        pRoot = doc.FirstChildElement("scene");

        Document * thisDoc = new Document();

        while (pRoot) {
            printf("Another Stuff\n");

            thisDoc->file1 = getElementText(pRoot- >FirstChildElement("model"));
            const char *file1 = Doc.file1.c_str();
            printf("%s\n", file1);
            printf("Stuff2\n");

            pRoot = pRoot->NextSiblingElement("scene");

        }
    }
}

XML-файл:

<scene>
  <model>plane.txt</model>
  <model>cone.txt</model>
  <model>box.txt</model>
  <model>sphere.txt</model>
</scene> 

Вывод, который я получил при тестировании: output

1 Ответ

0 голосов
/ 04 марта 2019

Я думаю, что вы путаете себя со всеми различными переменными, называемыми 'doc', тем или иным.

thisDoc->file1 = getElementText(pRoot- >FirstChildElement("model"));
const char *file1 = Doc.file1.c_str();

очевидно, должно быть это

thisDoc->file1 = getElementText(pRoot- >FirstChildElement("model"));
const char *file1 = thisDoc->file1.c_str();

И это

struct Document{
    std::string file1;
    std::string file2;
    std::string file3;
    std::string file4;

}Doc;

должно быть этим

struct Document {
    std::string file1;
    std::string file2;
    std::string file3;
    std::string file4;
};

Если вы действительно не хотели объявить глобальную переменную с именем Doc.Если вы это сделали, то это плохая идея.

Хороший выбор имени переменной важен, это действительно так.

...