我正在创建一个小部件,它将以非常格式化的方式显示XML字符串。要执行此操作,我使用QXmlStreamReader
和QXmlStreamWriter
(基于Format XML file in c++ or Qt的答案)并将文字提供给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)
但结果文字未将\n
转换为新行:
如果我手动输入一个包含\n
的字符串,它们将转换为新行:
textBrowser.setText("1\n2\n3\n4")
我已检查byteArray
的确切内容,以确保将\n
作为一个字符传递,而不是作为两个单独的'\'和'n'字符传递:
for i in range(0, byteArray.size()):
sys.stdout.write(byteArray.at(i))
按预期打印出XML字符串:
<?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>
我正在使用python 3.6和PyQt5
答案 0 :(得分:1)
您需要解码QByteArray
中的数据。这可以使用QTextStream
来完成,然后您可以轻松设置正确的编解码器:
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())