【问题标题】:Qt XML duplicate tagsQt XML 重复标签
【发布时间】:2020-08-06 13:38:03
【问题描述】:

我有一个 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)。如何复制一个简单的节点?

【问题讨论】:

    标签: c++ qt qt5


    【解决方案1】:

    问题出在这一行:

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

    insertAfter 方法接受两个参数 - 新节点和将作为新节点插入引用的节点。但是,这两个参数都必须是调用 insertAfter 的共同父级的子级。从原理上讲,您的代码类似于child-&gt;insertAfter(newChild, child),而它应该是parent-&gt;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;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 2019-04-30
      • 2017-01-02
      • 2013-06-22
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2015-09-20
      相关资源
      最近更新 更多