2

What is the tinyxml2 (v2) replacement for v1's TiXmlNode enumeration?
TinyXML v1 can switch on node type, but how to do the same with TinyXML v2's XMLNode.

switch (node->Type()) // v1 node type selector
{
    case TiXmlNode::DOCUMENT:
        wcout << L"Hello Document";
    break;
mpromonet
  • 11,326
  • 43
  • 62
  • 91
BSalita
  • 8,420
  • 10
  • 51
  • 68

1 Answers1

3

The base class XMLNode contains a number of virtual conversion methods, which return NULL or 0 unless the node is actually of the specified type.

For example, if you call ToText() on something that is actually an XMLText, you'll get a valid XMLText* result, otherwise you'll get NULL.

Here's the methods available (in XMLNode):

/// Safely cast to an Element, or null.
virtual XMLElement* ToElement() {
    return 0;
}
/// Safely cast to Text, or null.
virtual XMLText* ToText() {
    return 0;
}
/// Safely cast to a Comment, or null.
virtual XMLComment* ToComment() {
    return 0;
}
/// Safely cast to a Document, or null.
virtual XMLDocument* ToDocument() {
    return 0;
}
/// Safely cast to a Declaration, or null.
virtual XMLDeclaration* ToDeclaration() {
    return 0;
}
/// Safely cast to an Unknown, or null.
virtual XMLUnknown* ToUnknown() {
    return 0;
}

I'm not sure why this was done; perhaps the type enumeration wasn't that useful in practice, or maybe it's to support the internal XMLHandle class (which implements all those cast methods). To convert your code, you'd go from this:

switch (node->Type()) {
    case TiXMLNode::DOCUMENT:
        ...
        break;
    case TiXMLNode::TEXT:
        ...
        break;
    ...
}

into this:

XMLDocument *doc = node->ToDocument();
if (doc) {
    ...
}
XMLText *text = node->ToText();
if (text) {
    ...
}
congusbongus
  • 13,359
  • 7
  • 71
  • 99
  • 1
    Using a switch() statement on an enumeration is much more elegant. I hope the missing enum isn't because the author was trying to be minimalistic. If so, it's gone to far. Your answer gets me unblocked. Thank you. I'll checkmark your answer if nothing more elegant appears. – BSalita Dec 31 '13 at 06:07
  • @BSalita I suspect one motivation was that when querying for the node type, people were casting afterwards anyway, so the new method would save a line of code or two. Still, you'd need to ask the author for the real reasons why. – congusbongus Dec 31 '13 at 06:14
  • Had too many issues with tinyXml (v2) so I switched to pugiXml. pugiXml is working nicely. – BSalita Mar 19 '14 at 03:59
  • I agree that an enum is more elegant (and was baffled for a minute when upgrading to tinyxml2), however personally I've never needed a switch statement like that, i.e. I had a good idea of what type of element I need at that point (that'd be more SAX style, I guess), and this way I can save an operation (type enum check), and just keep using the result of To[Type](), if any. – zyndor May 15 '14 at 06:42