4

Using tinyXml2, I can parse

<MSG_TIME>2010-07-01 14:28:20</MSG_TIME>
just fine, but
<MSG_TIME></MSG_TIME>
and
<MSG_TIME/>
both throw exceptions in C++ when those are perfectly valid XML (to my knowledge). Does anyone have a fix or suggestion for this? I do not control the source of this XML, and I need to be error tolerant.
mpromonet
  • 11,326
  • 43
  • 62
  • 91
Mishka
  • 349
  • 1
  • 5
  • 10
  • Does the xsd you're using prevent empty elements -- http://stackoverflow.com/questions/4126646/prevent-empty-elements-in-xml-via-xsd? – hd1 Dec 31 '12 at 21:42
  • Report the bug to the authors of the library (and, if you can, fix it yourself). Meanwhile I would go for a better XML parsing library, like pugixml (my favorite). – Yakov Galka Dec 31 '12 at 21:47

1 Answers1

6

This answer assumes you're trying to load valid XML with an empty element.

XMLElement::GetText() returns nullptr if the element is empty, so you can do a simple check like this:

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();

This question actually pointed out a bug with the TinyXML2 tutorial I wrote a few months ago, so thanks for posting it! :)

GameDev
  • 136
  • 2
  • 6