首页 > 解决方案 > 为什么它不能正确解析 XML 文件?

问题描述

我想从 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> 

我在测试时得到的输出: 输出

标签: c++xmlstructtinyxml

解决方案


我认为您对所有称为“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. 如果你这样做了,那是个坏主意。

好的变量名选择很重要,确实如此。


推荐阅读