Format XML file in c++ or Qt

Using a QXmlStreamReader and QXmlStreamWriter should do what you want. QXmlStreamWriter::setAutoFormatting(true) will format the XML on different lines and use the correct indentation. With QXmlStreamReader::isWhitespace() you can filter out superfluous whitespace between tags.

QString xmlIn = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>"
                "<Analyser><JointDetails>              <Details><StdThickness>"
                " T </StdThickness><Thickness_num> 0.032 </Thickness_num>"
                "</Details>   </JointDetails></Analyser>";
QString xmlOut;

QXmlStreamReader reader(xmlIn);
QXmlStreamWriter writer(&xmlOut);
writer.setAutoFormatting(true);

while (!reader.atEnd()) {
    reader.readNext();
    if (!reader.isWhitespace()) {
        writer.writeCurrentToken(reader);
    }
}

qDebug() << xmlOut;

If you're using Qt, you can read it with QXmlStreamReader and write it with QXmlStreamWriter, or parse it as QDomDocument and convert that back to QString. Both QXmlStreamWriter and QDomDocument support formatting.


void format(void)
{
    QDomDocument input;

    QFile inFile("D:/input.xml");
    QFile outFile("D:/output.xml");

    inFile.open(inFile.Text | inFile.ReadOnly);
    outFile.open(outFile.Text | outFile.WriteOnly);

    input.setContent(&inFile);

    QDomDocument output(input);
    QTextStream stream(&outFile);
    output.save(stream, 2);
}