Agricola
Agricola

Reputation: 602

Check for Element Existence in TinyXML

I have been looking through the API for TinyXML and I can't find a way to check if an element exists before I try and get it by name. I have commented what I am looking for below:

#include <iostream>
#include "tinyxml.h"

int main()
{
  const char* exampleText = "<test>\
         <field1>Test Me</field1>\
          <field2>And Me</field2>\
         </test>";

  TiXmlDocument exampleDoc;
  exampleDoc.Parse(exampleText);

  // exampleDoc.hasChildElement("field1") { // Which doesn't exist
  std::string result = exampleDoc.FirstChildElement("test")
      ->FirstChildElement("field1")
      ->GetText();
  // }

  std::cout << "The result is: " << result << std::endl;
}

Upvotes: 1

Views: 824

Answers (1)

Agricola
Agricola

Reputation: 602

The FirstChildElement function will return a pointer, so that pointer can be used in the if-statement like so.

#include <iostream>
#include "tinyxml.h"

int main()
{
  const char* exampleText = "<test>\
         <field1>Test Me</field1>\
          <field2>And Me</field2>\
         </test>";

  TiXmlDocument exampleDoc;
  exampleDoc.Parse(exampleText);

  TiXmlElement* field1 = exampleDoc.FirstChildElement("test")
      ->FirstChildElement("field1");
  if (field1) {
    std::string result = field1->GetText();
    std::cout << "The result is: " << result << std::endl;
  }
}

Upvotes: 0

Related Questions