解析 tinyXML2 中的注释

parsing comment in tinyXML2

本文关键字:注释 tinyXML2 解析      更新时间:2023-10-16

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

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

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

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

谢谢

您可以使用

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

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

我刚刚在我的项目上创建了一个函数,可以递归地导航整个文档并删除注释。您可以使用它来查看如何获取对文档的任何评论...效仿上面那个家伙的例子..

代码波纹管:

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