【问题标题】:Check for Element Existence in TinyXML在 TinyXML 中检查元素是否存在
【发布时间】:2020-06-13 12:22:33
【问题描述】:

我一直在查看 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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      相关资源
      最近更新 更多