使用TinyXML解析XML元素?

时间:2014-07-16 20:03:21

标签: c++ xml 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);         
}

1 个答案:

答案 0 :(得分:0)

unit-&gt; value和unit-&gt;只有在&#39; unit&#39;时才应调用NextSibilingElement。不是NULL。对于您在此示例中使用的所有指针也是如此 编辑。在您的情况下,对于最后一个成分,单位为NULL,而unit-&gt;值应该是使应用程序崩溃的行。