【问题标题】:Why it's not parsing correctly the XML file?为什么它不能正确解析 XML 文件?
【发布时间】:2019-03-03 22:08:27
【问题描述】:

我想从 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++ xml struct tinyxml


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多