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;
有帮助吗?

解决方案

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) {
    ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top