1

I'm creating a widget that will display XML strings in a pretty formatted way. To do this I'm using a QXmlStreamReader and a QXmlStreamWriter (based on the answer from Format XML file in c++ or Qt) and feed the text to a QTextBrowser:

message = "<person><name>John</name><surname>Smith</surname><hobbies><sport>football</sport><sport>tenis</sport><activity>dancing</activity></hobbies></person>"
byteArray = QByteArray()
xmlReader = QXmlStreamReader(message)
xmlWriter = QXmlStreamWriter(byteArray)
xmlWriter.setAutoFormatting(True)
while (not xmlReader.atEnd()):
    xmlReader.readNext();
    if (not xmlReader.isWhitespace()):
        xmlWriter.writeCurrentToken(xmlReader)
prettyMessage = str(byteArray.data())
textBrowser.setText(prettyMessage)

But the resulting text doesn't convert \n to new lines:

enter image description here

If I input manually a string with \n in it, they are converted to new lines:

textBrowser.setText("1\n2\n3\n4")

enter image description here

I've checked the exact content of byteArray to make sure that the \n is passed as one character and not as two separate '\' and 'n' characters:

for i in range(0, byteArray.size()):
    sys.stdout.write(byteArray.at(i))

prints out the XML string as expected:

<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>John</name>
    <surname>Smith</surname>
    <hobbies>
        <sport>football</sport>
        <sport>tenis</sport>
        <activity>dancing</activity>
    </hobbies>
</person>

I'm using python 3.6 with PyQt5

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
SIMEL
  • 8,745
  • 28
  • 84
  • 130

1 Answers1

1

You need to decode the data in the QByteArray. This can be done using a QTextStream, which then allows you to easily set the right codec:

    byteArray = QByteArray()
    xmlReader = QXmlStreamReader(message)
    xmlWriter = QXmlStreamWriter(byteArray)
    xmlWriter.setAutoFormatting(True)
    while (not xmlReader.atEnd()):
        xmlReader.readNext();
        if (not xmlReader.isWhitespace()):
            xmlWriter.writeCurrentToken(xmlReader)

    stream = QTextStream(byteArray)
    stream.setCodec(xmlWriter.codec())
    textBrowser.setText(stream.readAll())
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • The line `stream.setCodec(xmlWriter.codec())` is not necesary. – SIMEL Nov 01 '17 at 07:42
  • @SIMEL. It is necessary if the xml writer uses a codec that is different to the default used by `QTextStream`. So it is generally better to always include that line. – ekhumoro Nov 01 '17 at 14:50