Qt XML 重复标签

Qt XML duplicate tags

我有一个 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 - 因为我的解决方案只是 return null。 (https://doc.qt.io/qt-5/qdomnode.html - insertAfter)。如何复制一个简单的节点?[​​=15=]

这一行有问题:

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