Crawl.W
Crawl.W

Reputation: 421

QDomElement QDomDocument::documentElement() return type is not reference,how it can change xml in QDomDocument?

As my title expressed, I use QDomDocument read-in xml file and use his function QDomDocument::documentElement() to achieve xml's root node Element. Like this:

QDomElement devices = docDetails_.documentElement();
QDomElement device = docDetails_.createElement("Device");
QDomAttr id = docDetails_.createAttribute("id");
id.setValue(QString::number(deviceInfo.id));
device.setAttributeNode(id);
devices.appendChild(device);

But the function's return type is not a reference type, why appendChild() can change QDomDocument's content?

Upvotes: 0

Views: 831

Answers (2)

goingjack
goingjack

Reputation: 1

auto a = doc.documentElement();
auto b = doc.documentElement();

use qtcreator debug and see a and b, expand them and see impl, you can see same address.

so, They use the same data structure, change a or b will also change doc.

QDomElement QDomDocument::documentElement() const
{
    if (!impl)
        return QDomElement();
    return QDomElement(IMPL->documentElement());
}
QDomElementPrivate* QDomDocumentPrivate::documentElement()
{
    QDomNodePrivate *p = first;
    while (p && !p->isElement())
        p = p->next;
    return static_cast<QDomElementPrivate *>(p);
}

Upvotes: 0

hank
hank

Reputation: 9853

The doc says (emphasis mine):

The parsed XML is represented internally by a tree of objects that can be accessed using the various QDom classes. All QDom classes only reference objects in the internal tree. The internal objects in the DOM tree will get deleted once the last QDom object referencing them and the QDomDocument itself are deleted.

So, calling QDomNode::appendChild on some QDom element will change its document internal xml tree.

Upvotes: 1

Related Questions