Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Keeping XML file formatting



  • Hello,
    I would like to read, modify, and write an XML file, without changing its formatting.
    The XML file is tracked by Git, so the goal is that no changes are made to the file, except for the data that has been modified.

    For now, I tried writing the QDomDocument to a QFile:

    QTextStream stream( &file );
        stream << doc.toString();
        file.close();
    

    But the formatting is changed even if nothing was modified (attribute order is swapped, empty lines are removed, indent is "fixed"...)

    I understand that the original formatting of the document is most probably not even present in the QDomDocument, but I wonder if there is a way to achieve this with QtXml?



  • @Fabien-B
    QDomDocument/other Qt XML readers/writers will be free to produce whatever they want that is legal as output format. There is no guarantee they will do anything about retaining the input textual format exactly as-is. [See e.g. https://forum.qt.io/topic/6202/solved-qdomdocument-attribute-ordering from 2011.]

    If you cannot afford any change in the output format, you won't be able to parse the input as XML and then use that to write it back. You will have to treat it as a text file in some shape or form, and manage the output format yourself.

    P.S.
    See however https://stackoverflow.com/questions/21535707/incorrect-order-of-attributes-in-qt-xml . That claims you can leverage QT_HASH_SEED to at least affect the attribute ordering. You could have a look. But I still think you will have a problem firstly if you read a document from another, non-Qt source, and secondly it may help with attribute ordering but won't with other things such as spacing and others.



  • Ok thank you @JonB , that's what I was thinking.
    I will start by accepting Qt's output, and wait to hear how loud users complain :-)


Log in to reply