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.

2
  • Does the xsd you're using prevent empty elements -- stackoverflow.com/questions/4126646/…? Commented Dec 31, 2012 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). Commented Dec 31, 2012 at 21:47

1 Answer 1

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! :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.