首页 > 解决方案 > 在 TinyXML 中检查元素是否存在

问题描述

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

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

标签: c++tinyxml

解决方案


FirstChildElement 函数将返回一个指针,因此该指针可以像这样在 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;
  }
}

推荐阅读