试图读取快速XML中的节点导致错误

Attempting to read nodes in Rapid XML resulting in error

本文关键字:节点 错误 XML 读取      更新时间:2023-10-16

我的程序中有一个类,它使用快速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-子句来提示错误。