检查 TinyXML 中的元素是否存在

Check for Element Existence in TinyXML

本文关键字:是否 存在 元素 TinyXML 检查      更新时间:2023-10-16

我一直在浏览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;
}

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