2014-07-16 47 views
0

我想解析一个XML文件,并从它获得某些属性来存储。如果每个元素都存在,我可以成功地解析文档,但是在某些情况下,某个元素对于特定节点不存在,因此我收到了一个分段错误,因为我正在创建一个指向不存在的元素的指针。以下是我正在解析的XML文件。使用TinyXML解析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> 

我不读<recipeinfo>元素,只需要在标题和成分。但是,最后一种成分没有单位,而只有食品数量和名称。达到最后的成分给我一个分段错误。我试图检查该元素是否存在,但我必须这样做的代码被跳过。

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);   
} 

回答

0

单位 - >值和单位 - > NextSibilingElement应该被称为仅当“单元”不为空。在这个例子中使用的所有指针都是一样的 编辑。在你的情况下,对于最后一个成分,单位是NULL,单位 - >值应该是使应用程序崩溃的行。