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