提问者:小点点

Qt XML重复标记


我有一个xml文件,只是想复制一些特定的节点:

来源(示例):

<1>
 <2>
 </2>
</1>

致:

<1>
 <2>
 </2>
 <2>
 </2>
</1>

我尝试了以下操作:

    for(int i = 0; i < xmlRoot.childNodes().count(); i++)    {
    if(xmlRoot.childNodes().at(i).isElement()){
        if(xmlRoot.childNodes().at(i).toElement().attribute("id") == "teamSection"){ //find goal element
            teamNode = xmlRoot.childNodes().at(i).cloneNode(); //copy element

            if(xmlRoot.childNodes().at(i).insertAfter(teamNode, xmlRoot.childNodes().at(i)).isNull()){
                qDebug() << "not worked";
            }
            else{
                qDebug() << "worked";
            }
            break;
        }
    }
}

但是我想我误解了refChiled-因为我的解决方案只是返回null。 (https://doc.qt.io/qt-5/qdomnode.html-insertAfter)。 如何复制一个简单的节点?


共1个答案

匿名用户

问题出在这一行:

xmlRoot.childNodes().at(i).insertAfter(teamNode, xmlRoot.childNodes().at(i))  

InsertAfter方法接受两个参数--新节点和将作为新节点插入引用的节点。 但是,这两个参数都需要是对其调用insertAfter的公共父级的子级。 从原理上讲,您的代码类似于child->insertAfter(newChild,child),而它应该是parent->insertAfter(newChild,child)。 您可以看看下面的代码:

for (int i = 0; i < xmlRoot.childNodes().count(); i++)
{
    if (xmlRoot.childNodes().at(i).isElement())
    {
        if(xmlRoot.childNodes().at(i).toElement().attribute("id") == "teamSection")
        {
            auto teamNode = xmlRoot.childNodes().at(i).cloneNode(); //copy element
            auto sibling = xmlRoot.childNodes().at(i);

            if (xmlRoot.insertAfter(teamNode, sibling).isNull())
            {
                qDebug() << "not worked";
            }
            else
            {
                qDebug() << "worked";
            }
            break;
        }
    }
}