使用TinyXML解析XML元素

Parsing XML elements using TinyXML?

本文关键字:元素 XML 解析 TinyXML 使用      更新时间:2023-10-16

我试图解析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应该是导致应用程序崩溃的那一行。