c++ - 在 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;
}
解决方案
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;
}
}
推荐阅读
- c# - Try-Catch 与 If-Else | 我应该争取在这个中使用 If-Else 还是只使用 Try-Catch?
- c# - 从 Messenger Webview 和 Botframework V4 发送和检索数据
- javascript - 允许特定 IP 地址访问我网站上的页面
- angularjs - TypeError: ($scope.values || []).map 不是函数
- mysql - Mysql Join查询与日期分组
- shell - 如何判断我的 C 程序是否是通过 shebang 调用的?
- javascript - After Effects 脚本手动工作,但在启动时不工作
- php - MySQL 选择根据表中的条目数创建排名...怎么做?
- matlab - 使用网格网格查找速度值时如何绘制二维平流问题?
- c# - 如何使用 REGEX 将提供为“FY18 Q1”的季度转换为 C# 中的“2018.4”?