使用RapidXML循环读取XML文件时出现空指针崩溃问题
问题:RapidXML循环处理XML文件时空指针崩溃
我正在开发一款读取XML文件列表并提取数据的程序,选用RapidXML库。第一个文件处理完全正常,但循环中打开下一个文件时,程序因RapidXML检测到子节点空指针崩溃。我试过把RapidXML相关声明放到全局作用域避免销毁,问题依旧。
以下是完整代码:
#include <filesystem> #include <string> #include <fstream> #include <streambuf> #include <sys/stat.h> #include "rapidxml.hpp" #include <iostream> using namespace rapidxml; using namespace std; namespace fs = std::filesystem; xml_document<> doc; xml_node<>* node; xml_node<>* child; int main() { int counter = 0; std::string path; struct stat sb; // 输入XML文件所在路径 cout << "Inserire il percorso dove sono presenti i file da leggere:\n"; do { if (counter > 0) cout << "Attenzione, percorso non valido!\n"; cin >> path; counter++; } while (stat(path.c_str(), &sb)); cout << "Percorso valido.\n"; // 遍历目录下的文件 for (const auto& entry : fs::directory_iterator(path)) { if (entry.path().extension().string().ends_with(".xml")) { if (entry.path().string().ends_with(".xml_metaDato.xml")) continue; else { cout << entry.path() << std::endl; std::ifstream t(entry.path().filename()); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); str.append("\0"); doc.parse<0>(&str[0]); // 0表示默认解析标志 // if (doc.first_node() == nullptr) cout << "Trying to reference a null pointer"; // cout << doc.first_node()->name() << "\n"; node = doc.first_node(); for (child = node->first_node(); child; child = child->next_sibling()) { cout << child->name() << std::endl; } doc.clear(); t.close(); } } } }
问题出在以下代码段,打开新文件后读取数据时触发空指针崩溃:
node = doc.first_node(); for (child = node->first_node(); child; child = child->next_sibling()) { cout << child->name() << std::endl; }
内容的提问来源于stack exchange,提问作者randomizzatore
相关产品推荐
相关产品推荐

