使用 tinyXml2,我可以解析
<MSG_TIME>2010-07-01 14:28:20</MSG_TIME>很好,但是
<MSG_TIME></MSG_TIME>和
<MSG_TIME/>当它们是完全有效的 XML(据我所知)时,它们都会在 C++ 中抛出异常。有没有人对此有修复或建议?我不控制这个 XML 的来源,我需要容错。
此答案假定您正在尝试使用空元素加载有效的 XML。
XMLElement::GetText()nullptr如果元素为空则返回,因此您可以进行如下简单检查:
std::string szData;
// Get the element
XMLElement pElement = xmlDoc.FirstChildElement("MyElement");
// Check whether the element contains data & if so, extract it as text
if (pElement->GetText() != nullptr) szData = poElement->GetText();
Run Code Online (Sandbox Code Playgroud)
这个问题实际上指出了我几个月前写的TinyXML2 教程的一个错误,所以感谢发布它!:)