将节点添加到现有根元素

2023-12-25

我正在尝试使用 C++ QDOM 元素将子节点添加到现有根节点,但不成功。我的xml会是这样的。

<setting>
    <setting1 length="5" />
    <setting1 width="5" />
</setting>

我正在尝试添加,所以它可能是这样的。

<setting>
    <setting1 length="5" />
    <setting1 width="5" />
    <setting2 length="5" />
    <setting2 width="5" />
</setting>

我当前的代码是

 //If firstCall, then create new file, succeeding calls will append.
    if (firstCall) {
        // Error while loading file
        if (!xmlFile.open(QFile::WriteOnly | QFile::Text))
        {
            qDebug() << "Already opened or there is another issue";
            xmlFile.close();
        }
        else
        {
            root = document.createElement("setting"); //New element
            document.appendChild(root);
            viewName = "setting1";
        }
    }
    else
    {
        // Error while loading file
        if (!xmlFile.open(QIODevice::Append))
        {
            qDebug() << "Already opened or there is another issue";
            xmlFile.close();
        }
        else 
        {
            root = document.createElement("setting"); //??????
            viewName = "setting2";
        }
    }

    //add it to document
    document.appendChild(root);
    // save values
    QDomElement setting = document.createElement(viewName);
    setting.setAttribute("Length", "5");
    root.appendChild(setting);
    setting = document.createElement(viewName);
    setting.setAttribute("Width", "5");
    root.appendChild(setting);
    xmlContent << document.toString();
    xmlFile.close();

我可以生成第一个 xml 示例,但不能生成第二个 xml。我不确定我是否还会使用root = document.createElement("setting");如果 xml 已经存在。请帮忙。谢谢。


我想你应该创建两个子元素,其名称为:

viewName1 = "setting1";
viewName2 = "setting2";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将节点添加到现有根元素 的相关文章

随机推荐