我的程序中有一个使用Rapid XML将数据写入文件的类。此过程运行良好。但是,当我尝试读取相同的数据时,我的程序将始终被内部错误捕获代码暂停,并解释为“下一个同级返回NULL,但无论如何仍试图读取值”。
if (xmlFile.good())
{
vector<char> buffer((istreambuf_iterator<char>(xmlFile)), istreambuf_iterator<char>());
buffer.push_back('\0');
doc.parse<0>(&buffer[0]);
root_node = doc.first_node("CityData");
for(xml_node<> * bound_node = root_node->first_node("Boundaries"); bound_node; bound_node = bound_node->next_sibling())
{
if (bound_node->first_attribute("enabled")->value() != NULL)
{
int enabled = atoi(bound_node->first_attribute("enabled")->value());
if (enabled == 1)
boundaries = true; // Program globals
}
}
if (boundaries)
{
for(xml_node<> * dimen_node = root_node->first_node("Dimensions"); dimen_node; dimen_node = dimen_node->next_sibling())
{
cityDim.x = atoi(dimen_node->first_attribute("x-val")->value()); // Program globals
cityDim.y = atoi(dimen_node->first_attribute("y-val")->value());
}
}
数据如何显示在XML文件中的示例:
<CityData version="1.0" type="Example">
<Boundaries enabled="1"/>
<Dimensions x-val="1276" y-val="688"/>
如果在任何一个循环尝试重复并查看值之前添加一个断点,我们可以看到它们是从第一次迭代中读取的,但是循环的结束条件似乎不正确,并在next_sibling()
发生错误时发生。我无法理解该问题,因为循环的代码是从完全未经修改的示例中复制的(除了变量重命名),并且对我来说似乎正确(将其修改为node != NULL
)无济于事。
在bound_node
-loop中,变量bound_node
首先指向,<Boundaries enabled="1">
并且您可以读取名称为的属性enabled
。在对的调用之后next_sibling()
,bound_node
指向<Dimensions .../>
和对的调用first_attribute("enabled")
将返回空指针,因为此xml节点没有具有该名称的属性,而对的后续调用value()
将导致程序崩溃。
我不明白您为什么要在所有节点上编写循环。如果xml文件看起来像这样
<CityData version="1.0" type="Example">
<Boundaries enabled="1"/>
<Dimensions x-val="1276" y-val="688"/>
</CityData>
然后,您可以像这样提取值:
xml_node<> const * bound_node = root_node->first_node("Boundaries");
if (bound_node)
{
xml_attribute<> const * attr_enabled = bound_node->first_attribute("enabled");
if (attr_enabled)
{
int enabled = atoi(attr_enabled->value());
if (enabled == 1)
boundaries = true;
}
}
if (boundaries)
{
xml_node<> const * dimen_node = root_node->first_node("Dimensions");
if (dimen_node)
{
xml_attribute<> const * xval = dimen_node->first_attribute("x-val");
xml_attribute<> const * yval = dimen_node->first_attribute("y-val");
if (xval && yval)
{
cityDim.x = atoi(xval->value());
cityDim.y = atoi(yval->value());
}
}
}
}
当然,您可以编写其他条款来表示错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句