Add node to Existing Root Element

77 Views Asked by At

I am trying to add child node to an existing root node using C++ QDOM element but unsuccessful. My xml would be like this.

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

and I am trying to add so it could be like this.

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

My current code is

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

I can generate the first xml sample, but not the 2nd xml. I am not sure if I will still use root = document.createElement("setting"); if xml is already existing. Kindly help please. thank you.

1

There are 1 best solutions below

0
On

I suppose you should create two child Elements with the names:

viewName1 = "setting1";
viewName2 = "setting2";