How can I set the inner HTML in a QDomElement?

When I’m using QWebElement I have the method QWebElement::setInnerXml, there is some similar method in QDomElement?

有帮助吗?

解决方案

There's no API to "inject" XML snippets as text into a QDomDocument (or QXmlStreamWriter). One has to use the API and create the nodes programmatically.

其他提示

Assuming you have a string to start with, my current solution is to generate a DOM tree from it, import that tree in a fragment, then copy those in the right place (you must have an import which is why you need an intermediate fragment. Quite unfortunate if you ask me.)

// assuming that 'n' is the node you are replacing or at least inserting after
// 'parent' is the parent of 'n'
// 'result' is the string to replace 'n' or insert after 'n'
QDomDocument doc_text("snap");
doc_text.setContent("<text>" + result + "</text>", true, NULL, NULL, NULL);
QDomDocumentFragment frag(xml.createDocumentFragment());
frag.appendChild(xml.importNode(doc_text.documentElement(), true));
QDomNodeList children(frag.firstChild().childNodes());
const int max(children.size());
QDomNode previous(n);
for(int i(0); i < max; ++i)
{
    QDomNode l(children.at(0));
    parent.insertAfter(children.at(0), previous);
    previous = l;
}
// if you are replacing, then delete node n as well
parent.removeChild(n);

Note that the <text> tag is used so that way result does not need to be a tag, it could just be text and it will still work.

Obviously, if you have a fragment or XML from another document to start with, ignore the code that creates that code in the doc_text object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top