You can drop document as parameter because each QDomNode has method ownerDocument()
. QDomElement
inherits QDomNode
so it's also accessible from parent
parameter. Check QDomNode documentation.
Create QDomNodes without QDomDocument
Question
Is it possible to create a QDomElement without having a QDomDocument available? For example, here is a function that is expected to build a node tree under the element parent
:
void buildResponse (QDomDocument &doc, QDomElement &parent) {
QDomElement child = doc.createElement("child");
parent.appendChild(child);
}
The only reason I have to pass doc
is to use it as a factory to create elements that the function adds under parent
. In the application I'm working on now, it would simplify my implementation slightly if I didn't have to lug the QDomDocument
around.
Is there a way to create nodes without having a document available?
La solution
Autres conseils
I needed to do something similar in my project, but I did not not have access to the parent document at all. I just wanted to return a QDomNode and add it to a parent tree in the calling method. I was migrating from libxml2 and changing this behavior required a large redesign of the code. So the above solution did not work for me.
I solved it instead by creating a temporary QDomDocument, then created the subtree using that. Back in the calling method, I have imported it to the parent document. Here is an example:
#include <QtXml>
#include <iostream>
using namespace std;
QDomNode TestTree(void) {
QDomDocument doc("testtree");
QDomElement testtree=doc.createElement("testing");
testtree.setAttribute("test","1");
doc.appendChild(testtree);
QDomElement testchild1 = doc.createElement("testje");
testtree.appendChild(testchild1);
QDomElement testchild2 = doc.createElement("testje");
testtree.appendChild(testchild2);
return testtree;
}
int main (int argc, char **argv) {
QDomDocument doc("MyML");
QDomElement root = doc.createElement("MyML");
doc.appendChild(root);
QDomElement tag = doc.createElement("Greeting");
root.appendChild(tag);
QDomText t = doc.createTextNode("Hello World");
tag.appendChild(t);
QDomNode testtree = TestTree();
QDomNode testtree_copy=doc.importNode(testtree,true);
root.appendChild(testtree_copy);
QString xml = doc.toString();
cout << qPrintable(xml) << endl;
}