使用TinyXML解析XML元素
Parsing XML elements using TinyXML?
我试图解析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);
}
unit->value和unit->NextSibilingElement应该只在'unit'不为NULL时调用。在本例中使用的所有指针也是如此编辑。在您的例子中,对于最后一个成分,unit是NULL, unit->value应该是导致应用程序崩溃的那一行。
相关文章:
- 使用 libxml2 解析 XML 文件时缺少元素值
- 使用提升属性树检查 xml 文件中是否存在元素
- 使用 qt c++ 检查 Xml 中是否存在根元素
- 使用 TinyXML 解析 XML 元素 - 无限循环
- 如何使用libxml2从C 中的XML文件中检索节点和特定元素字符串而不使用XPATH
- 如何使用XPath使用libxml2从C 中的XML文件中检索节点和特定元素字符串
- 正在更新微小Xml元素中的数据
- 忽略GSOAP中的未知XML元素节点
- 将xml字符串嵌套到xml元素中的语法
- PugiConvert xml元素内容到C++数组
- 有人可以解释为什么我的XML解析器跳过这些HTML元素的原因
- 如何使用 qt 删除嵌套的 xml 元素
- CodeSynthesis XSD CXX 不解析 XML 文件,表示未声明属性/元素
- 使用 cpp 在 opencv 中的 xml 文件中追加元素
- Qt XML读取元素,并且只获取根
- Qt更新单个XML元素
- 忽略xml元素中的字符
- TinyXML2 -在XML中间插入元素
- 使用TinyXML解析XML元素
- 使用TinyXML解析XML元素