检查 TinyXML 中的元素是否存在

Check for Element Existence in TinyXML

我一直在 API 中寻找 TinyXML,但在尝试按名称获取元素之前找不到检查元素是否存在的方法。我在下面评论了我要找的东西:

#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;
}

FirstChildElement 函数将 return 一个指针,这样就可以像这样在 if 语句中使用该指针。

#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;
  }
}