Format XML file in c++ or Qt

ⅰ亾dé卋堺 提交于 2019-12-05 06:16:22

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);
}

If you want a simple robust solution that does not rely on QT, you can use libxml2. (If you are using QT anyway, just use what Frank Osterfeld said.)

xmlDoc* xdoc = xmlReadFile(BAD_CAST"myfile.xml", NULL, NULL, 0);
xmlSaveFormatFile(BAD_CAST"myfilef.xml", xdoc, 1);
xmlFreeDoc(xdoc);

Can I interest you in my C++ wrapper of libxml2?

Edit: If you happen to have the XML string in memory, you may also use xmlReadDoc... But it doesn't stop there.

Utilising C++ you can add a single character between each instance of >< for output: by changing >< to >\n< (this adds the non-printing character for a newline) each tag will print onto a new line. There are API ways to do this however as mentioned above, but for a simple way to do what you suggest for console output, or so that the XML flows onto new lines per tag in something like a text editor, the \n should work fine.

If you need a more elegant output, you can code a method yourself using \n (newline) and \t (tab) to lay out your output, or utilise an api if you reeqire a more elaborate representation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!