Bruno
Bruno

Reputation: 53

Why it's not parsing correctly the XML file?

I want to get from a xml file the name of a file, but it seems that it is not storing any information about the file.

Struct to store the name of the file(or files later):

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

}Doc;

Get the element from the xml file:

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

    return value;
}

Parsing the xml file:

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");

        }
    }
}

the XML file is:

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

The output I got when testing: output

Upvotes: 0

Views: 204

Answers (1)

john
john

Reputation: 87959

I think you're confusing yourself with all the various variables called 'doc' something or other.

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

obviously should be this

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

And this

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

}Doc;

should be this

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

Unless you really did mean to declare a global variable called Doc. If you did then that's a bad idea.

Good variable name choice is important, it really is.

Upvotes: 1

Related Questions