I have an XML file where outputs are not getting formatted. That means all the outputs are in a single line but I want to break it tag by tag.
For e.g. -
<?xml version="1.0" encoding="UTF-8" standalone="no" ?><Analyser> <JointDetails> <Details><StdThickness> T </StdThickness><Thickness_num> 0.032 </Thickness_num></Details> </JointDetails></Analyser>
But i want to do it like this ::
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Analyser>
<JointDetails>
<Details>
<StdThickness> T </StdThickness>
<Thickness_num> 0.032 </Thickness_num>
</Details>
</JointDetails>
</Analyser>
Please don't suggest to do it while writing the XML file because this XML file is already there but now I have to format it as mentioned above.
To write XML document with QXmlStreamWriter, you start a document with the writeStartDocument() function and end it with writeEndDocument(), which implicitly closes all remaining open tags.
Qt provides two general-purpose sets of APIs to read and write well-formed XML: stream based and DOM based. Qt also provides specific support for some XML dialects.
Click on Plugins Menu, Select XML Tools -> Pretty Print or Pretty Print - Indent attributes or Pretty Print - Indent only option or you can choose shortcut key CTRL+ALT+Shift+A or CTRL+ALT+Shift+A command.
XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data. XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With