Search code examples
c++xmllogictinyxml

Runtime error with tinyXML element access


yester day was my first attempt. I am trying to catch the variable "time" in the following "new.xml" file

<?xml version="1.0" standalone=no>
<main>
 <ToDo time="1">
  <Item priority="1"> Go to the <bold>Toy store!</bold></Item>
  <Item priority="2"> Do bills</Item>
 </ToDo>
 <ToDo time="2">
  <Item priority="1"> Go to the Second<bold>Toy store!</bold></Item>
 </ToDo>
</main>

Here is my code

TiXmlDocument doc("new.xml");
TiXmlNode * element=doc.FirstChild("main");
element=element->FirstChild("ToDo");
string temp=static_cast<TiXmlElement *>(element)->Attribute("time");

But I am getting run time errors from the third and fourth lines. Can anybody shed a light on this isssue?


Solution

  • It seems to me that you forgot to load the file. Normally I do something along these lines:

    TiXmlDocument doc("document.xml");
    bool loadOkay = doc.LoadFile(); // Error checking in case file is missing
    if(loadOkay)
    {
        TiXmlElement *pRoot = doc.RootElement();
        TiXmlElement *element = pRoot->FirstChildElement();
        while(element)
        {
            string value = firstChild->Value(); // In your example xml file this gives you ToDo
            string attribute = firstChild->Attribute("time"); //Gets you the time variable
            element = element->NextSiblingElement();
        }
    }
    else
    {
        //Error conditions
    } 
    

    Hope this helps