【问题标题】:Parsing XML elements using TinyXML?使用 TinyXML 解析 XML 元素?
【发布时间】:2014-07-16 20:03:20
【问题描述】:

我正在尝试解析一个 xml 文件并从中获取某些属性以进行存储。如果每个元素都存在,我可以成功解析文档,但在某些情况下,特定节点不存在元素,因此我收到分段错误,因为我正在创建指向不存在的元素的指针。以下是我正在解析的 XML 文件。

<recipe>
  <title>Hippie Pancakes</title>

  <recipeinfo>
    <blurb>Socially conscious breakfast food.</blurb>

    <author>David Horton</author>

    <yield>12 to 16 small pancakes, enough for two hippies</yield>

    <preptime>10 minutes</preptime>
  </recipeinfo>

  <ingredientlist>
    <ingredient><quantity>1</quantity> <unit>C.</unit> <fooditem>unbleached
     wheat blend flour</fooditem></ingredient>

    <ingredient><quantity>2</quantity> <unit>tsp.</unit> <fooditem>baking
    powder</fooditem></ingredient>

    <ingredient><quantity>1</quantity> <unit>tsp.</unit> <fooditem>unrefined
    sugar</fooditem></ingredient>

     <ingredient><quantity>1/4</quantity> <unit>tsp.</unit> <fooditem>coarse
    kosher salt</fooditem></ingredient>

    <ingredient><quantity>1</quantity> <fooditem> free-range egg</fooditem></ingredient>


   </ingredientlist>
 </recipe>

我不看&lt;recipeinfo&gt;元素,只需要标题和成分。但是,最后一种成分没有单位,只有数量和食物的名称。达到最后一个成分会给我一个分段错误。我正在尝试检查该元素是否存在,但我必须这样做的代码被跳过了。

TiXmlElement* recipeinfo = title->NextSiblingElement();
TiXmlElement* ingredientlist = recipeinfo->NextSiblingElement();
TiXmlElement* ingredient = ingredientlist->FirstChildElement();
if (ingredient){
    iterate(ingredient);
}

 void iterate(TiXmlElement* ingredient){
    TiXmlElement* quantity = ingredient->FirstChildElement("quantity");
    if (quantity->NextSiblingElement()){
        double quantity_ = atof(quantity->GetText());
        cout << " " << quantity_ << flush;  

        TiXmlElement* unit = quantity->NextSiblingElement("unit");
        string name = unit->Value();
        cout << name;
        if (unit->NextSiblingElement()){

            string unit_ = unit->GetText();
            cout << " " << unit_ << flush;

            TiXmlElement* fooditem = unit->NextSiblingElement("fooditem");

            string fooditem_ = fooditem->GetText();
            cout << " " << fooditem_ << flush;
        }  
        else{
            TiXmlElement* fooditem = quantity->NextSiblingElement("fooditem");
            string fooditem_ = fooditem->GetText();
            cout << fooditem->Value();
            cout << " " << fooditem_ << flush;
        }
    }

    TiXmlElement* nextIngredient = ingredient->NextSiblingElement();

    if (ingredient->NextSiblingElement())
        iterate(nextIngredient);         
}

【问题讨论】:

    标签: c++ xml tinyxml


    【解决方案1】:

    unit->value 和 unit->NextSibilingElement 仅在 'unit' 不为 NULL 时才应调用。您在此示例中使用的所有指针也是如此 编辑。在您的情况下,对于最后一个成分,unit 为 NULL,并且 unit->value 应该是导致应用程序崩溃的行。

    【讨论】:

      猜你喜欢
      • 2011-09-25
      • 2019-06-24
      • 2010-10-21
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多