0

I'm just getting started with the XML parsing library, but I'm having trouble getting started. (The learning curve, I guess) More specifically, I'm dealing with an exception when trying to get an element and use it. Right now I have this line:

tinyxml2::XMLElement *firstEvent = doc.FirstChildElement("EVENTS")->FirstChildElement();

Which throws a memory exception. For some reason, I can't show my XML code, but the structure is

file->EVENTS->event->some more content

So what this seems like to me is that the parser can't access the "event" element. What could be causing this? What am I doing wrong?! Any help would be very nice!

1 Answers1

1

Assuming this is your xml content:

<events>
  <event> "Move" <\event>
  <event> "Walk" <\event>
  <event> "Run" <\event>
<\events>

Test if the XmlElement is not NULL before iteration to avoid throwing exception: C++ code snippet can look like this:

XmlElement* elem = doc.FirstChildElement("events");
if(elem != NULL)
{
   for (XmlElement* e = elem->FirstChildElement("event"); e != NULL; e = e->NextSiblingElement("event"))
   {
        const char *c = e->GetText(); // if its an attrib use e->Attribute("event-type");
        /* more  */
   }
}
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
seccpur
  • 4,996
  • 2
  • 13
  • 21
  • Ok, makes sense! But that still won't solve the problem. Even if it doesn't throw the exception, it doesn't access the elements. Why would it not be accessing those? (And yes, the description of my XML content is correct. Except each event has content inside it too.) – Eyesight Technology Feb 03 '18 at 20:29
  • I've actually attempted this now, and have realized that the exception is thrown in the definition itself, meaning that `tinyxml2::XMLElement *firstEvent = doc.FirstChildElement("EVENTS")->FirstChildElement();` is the line throwing the exception, and therefore an IF statement can never be run regardless... Weird! Any thoughts? – Eyesight Technology Feb 04 '18 at 05:08
  • You are nesting the FirstChildElement(). If the first call returns a null, then exception will be thrown since a null object is trying to make a call. BTW element names are case sensitive. – seccpur Feb 04 '18 at 12:58
  • I've found that by just making it go to "EVENTS" and not going inside (to the first element contained) it does not throw an exception, as in the contents inside throw null. – Eyesight Technology Feb 04 '18 at 20:19
  • @EyesightTechnology Yes. As per the answer that conveys the better way than daisy chaining. Doesn't really work in this case. – Andrew Truckle Mar 06 '18 at 12:21