【发布时间】: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>
我不看<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);
}
【问题讨论】: