试图读取快速XML中的节点导致错误
Attempting to read nodes in Rapid XML resulting in error
我的程序中有一个类,它使用快速XML将数据写入文件。这个过程很好。然而,当我试图读取相同的数据时,我的程序将总是被内部错误捕获代码停止,解释"下一个兄弟返回NULL,但试图读取值"。
if (xmlFile.good())
{
vector<char> buffer((istreambuf_iterator<char>(xmlFile)), istreambuf_iterator<char>());
buffer.push_back(' ');
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
-循环中,变量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());
}
}
}
}
当然,你可以写一些else-子句来提示错误。
相关文章:
- 删除链表中的节点 - 分段错误
- C++错误(从不兼容的类型"void"分配给树节点*)
- 节点 API 抛出自己的错误消息,而不是自己的错误消息
- 树节点之间的最大距离中的运行时错误
- V8 - 节点C++插件 - 在构造函数中引发异常会导致"致命错误:v8::ToLocalChecked Em
- 在BST堆中删除节点免错误
- 解析序列/映射节点时出现无效的 yaml 节点错误
- 节点C++源代码编译错误
- 错误:无法从节点*转换为节点 c++?
- 节点插件编译错误
- 当我将字符串放入节点>名称时,为什么会出现分段错误(核心转储)?
- 分段错误,同时减去链表的 2 个连续节点
- 在 BST 中插入节点时出现逻辑错误
- 当我返回节点*时,C++中出现未知类型错误
- 插件中节点.js/Nan 回调C++不频繁的隔离错误
- YAML-CPP 节点诊断有意义的错误
- 使用括号会在声明新节点时会产生错误
- C++为什么创建一个新节点来删除堆栈上的节点是错误的
- 在链表运行时插入节点错误
- 无法在 Borland C++ 中将'void*'转换为 *poly 节点错误