繁体   English   中英

解析 tinyXML2 中的注释

[英]parsing comment in tinyXML2

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

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

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

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

谢谢

您可以使用XMLNode::FirstChild()XMLNode::NextSibling()遍历所有子节点。 使用dynamic_cast测试node是否为注释。

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

我只是通过阅读文档来弥补这一点,因此代码中可能存在错误。

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

代码如下:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM