我正在尝试解析一个xml文件:
<?xml version="1.0"?>
<settings>
<output>test.dat</output>
<width>5</width>
<depth>4</depth>
<height>10</height>
</settings>
main:
int _tmain(int argc, wchar_t* argv[])
{
std::string SettingsFile = "settings.xml";
rapidxml::xml_document<> doc;
char* settings = FileHandler::readFileInChar(SettingsFile.c_str());
std::cout << strlen(settings); // Output 1
doc.parse<0 | rapidxml::parse_no_data_nodes>(settings);
std::cout << strlen(settings); // Output 2
....
}
Output1: 129
Output2: 31
助手函数:
static char* readFileInChar(const char* p_pccFile)
{
char* cpBuffer;
size_t sSize;
std::ifstream ifFileToRead;
ifFileToRead.open(p_pccFile, std::ios::binary);
if(ifFileToRead.is_open()) {
sSize = getFileLength(&ifFileToRead);
cpBuffer = new char[sSize+1];
ifFileToRead.read(cpBuffer, sSize);
ifFileToRead.close();
}
cpBuffer[sSize] = '\0';
return cpBuffer;
}
static size_t getFileLength(std::ifstream* file)
{
file->seekg(0, std::ios::end);
size_t length = file->tellg();
file->seekg(0, std::ios::beg);
return length;
}
当我尝试访问任何节点时,这会导致异常。我想我在这里遗漏了一些明显的东西,但到目前为止我还不明白。
如果我尝试像这样的东西:
std::cout << doc.first_node("output")->value();
我在读取位置0x00000004时收到访问冲突的消息。
发布于 2012-09-17 22:24:44
该文档没有名为"output“的节点。该文档有一个名为"settings“的节点,而该节点又有一个名为"output”的节点。下面的代码
std::ifstream file("settings.xml");
std::vector<char> content = std::vector<char>(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
content.push_back('\0');
rapidxml::xml_document<> doc;
doc.parse<0 | rapidxml::parse_no_data_nodes>(&content[0]);
rapidxml::xml_node<> * root = doc.first_node();
for (rapidxml::xml_node<> * node = root->first_node(); node; node = node->next_sibling())
{
std::cout << "value of <" << node->name() << "> is " << node->value() << std::endl;
}
打印
value of <output> is test.dat
value of <width> is 5
value of <depth> is 4
value of <height> is 10
在我的机器上。
编辑:如果您查看调试器中的"content“,您可以清楚地看到rapidxml在其中插入'\0‘的位置。
https://stackoverflow.com/questions/12460385
复制相似问题