QDomDocument toString

927 views Asked by At

Running the below code does not produce the same ordering of attributes each time. Why is this happening?

QDomDocument dom;
QDomElement element= dom.createElement("MyElement");
element.setAttribute("attr1", "foo");
element.setAttribute("attr2", "bar");
element.setAttribute("attr3", "hello");
dom.appendChild(element);

QString text = dom.toString();

I am aware that the xml specification says ordering of attribute is not significant but I expected QDomDocument::toString to produce the same result each time given the same input.

This is important because I would like to unit test the produced data but if the data changes between runs that makes it more difficult.

1

There are 1 answers

0
peppe On BEST ANSWER

QDomDocument stores the attributes of a given node in a QHash, which protects itself against algoritmic complexity attacks by salting the hash calculation of any given key with a random salt.

Of course, for testing purposes this is a counter feature. Solution: run your testcase with the environment variable QT_HASH_SEED set to some integer (0?), which will be then used as the salt.

Setting that variable out of process is OK and works, but if you want to set it for the current process (via qputenv or similar), note that you need to do that before any QHash instance is built (either by you, or by Qt itself, or via global code executed before main by you or some other loaded library, and so on). So be very very careful. Assuming other libraries are smart, force its execution before calling any Qt methods.