0

I have problem with parsing XML comment. How can i properly access to comment? Or is even possible to read comment with tinyXML2?

<xml>
<foo> Text <!-- COMMENT --> <foo2/></foo>
</xml>

I created XMLElement *root = xmlDoc->FirstChildElement("foo"); XMLElement *child = root->FirstChildElement();

From child element i get foo2 element, What is propper way to read comment element from file.

Thanks

gomess
  • 83
  • 1
  • 8
  • Welcome to Stack Overflow. A question like this isn't really answerable and usually attracts downvotes and close votes. . See how to create a [mcve]. – Captain Giraffe Apr 09 '17 at 10:02

2 Answers2

1

You can use XMLNode::FirstChild() and XMLNode::NextSibling() to loop through all child nodes. Use dynamic_cast to test if node is a comment.

if( const XMLElement *root = xmlDoc->FirstChildElement("foo") )
{
    for( const XMLNode* node = root->FirstChild(); node; node = node->NextSibling() )
    {
        if( auto comment = dynamic_cast<const XMLComment*>( node ) )
        {
            const char* commentText = comment->Value();
        }   
    }
}

I've made this up just from reading the documentation, so there might be mistakes in the code.

zett42
  • 25,437
  • 3
  • 35
  • 72
0

I just created a function on my project that navigates the entire document recursively and get rid of comments. You can use that to see how you can pick up any comment on the document... followed the example of the fellow above..

Code bellow:

// Recursively navigates the XML and get rid of comments.
void StripXMLInfo(tinyxml2::XMLNode* node)
{
    // All XML nodes may have children and siblings. So for each valid node, first we
    // iterate on it's (possible) children, and then we proceed to clear the node itself and jump 
    // to the next sibling
    while (node)
    {
        if (node->FirstChild() != NULL)
            StripXMLInfo(node->FirstChild());

        //Check to see if current node is a comment
        auto comment = dynamic_cast<tinyxml2::XMLComment*>(node);
        if (comment)
        {
            // If it is, we ask the parent to delete this, but first move pointer to next member so we don't get lost in a NULL reference
            node = node->NextSibling();
            comment->Parent()->DeleteChild(comment);
        }
        else
            node = node->NextSibling();
    }
}