我想从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>
答案 0 :(得分: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
的全局变量。如果您这样做了,那将是个坏主意。
选择正确的变量名很重要,这确实很重要。