【问题标题】:parsing comment in tinyXML2在 tinyXML2 中解析注释
【发布时间】:2017-04-09 09:54:11
【问题描述】:

我在解析 XML 注释时遇到问题。我怎样才能正确访问评论? 或者甚至可以用 tinyXML2 阅读评论?

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

我创造了 XMLElement *root = xmlDoc->FirstChildElement("foo"); XMLElement *child = root->FirstChildElement();

从子元素我得到 foo2 元素,从文件中读取注释元素的正确方法是什么。

谢谢

【问题讨论】:

  • 欢迎来到 Stack Overflow。像这样的问题并不是真正可以回答的,通常会吸引反对票和接近投票。 .了解如何创建minimal reproducible example

标签: c++ tinyxml2


【解决方案1】:

您可以使用XMLNode::FirstChild()XMLNode::NextSibling() 循环遍历所有子节点。使用dynamic_cast 测试节点是否为评论。

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

我只是通过阅读documentation 编造出来的,因此代码中可能存在错误。

【讨论】:

    【解决方案2】:

    我刚刚在我的项目中创建了一个函数,它可以递归地导航整个文档并摆脱 cmets。您可以使用它来查看如何获取对文档的任何评论...按照上面那个人的示例..

    代码如下:

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

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 2012-01-04
      • 2011-10-27
      • 1970-01-01
      • 2010-11-09
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多