XML To FastInfoset Converter Example

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../../shared")

from DevMachines import __pyside2__, __pyside6__
from DevMachines import QtitanBase
from DevMachines.QtitanBase import Qtitan, XmlStreamReader, XmlStreamWriter
from DevMachines.QtitanFastInfoset import getFastInfosetVersion, FastInfosetStreamWriter, FastInfosetStreamReader

if __pyside2__:
    from PySide2 import QtCore
    from PySide2.QtCore import (Qt, QByteArray, QBuffer, QIODevice, QTextStream,
                                QDir, QFile, QXmlStreamReader, QXmlStreamWriter)
    from PySide2.QtWidgets import (QWidget, QApplication, QFileDialog, QMessageBox)

if __pyside6__:
    from PySide6 import QtCore
    from PySide6.QtCore import (Qt, QByteArray, QBuffer, QIODevice, QTextStream,
                                QDir, QFile, QXmlStreamReader, QXmlStreamWriter)
    from PySide6.QtWidgets import (QWidget, QApplication, QFileDialog, QMessageBox)

from DemoMainWindow import DemoMainWindow
from ui_mainwindow import Ui_MainForm as ui
from xmlsyntaxhighlighter import XmlSyntaxHighlighter

def xml_converter(reader, writer):
    while reader.readNext() != QXmlStreamReader.Invalid:
        token = reader.tokenType()
        if token == QXmlStreamReader.NoToken:
            assert(False)
        elif token == QXmlStreamReader.StartDocument:
            version = reader.documentVersion()
            if not version:
                version = "1.0"
            if reader.isStandaloneDocument():
                writer.writeStartDocument(version, reader.isStandaloneDocument())
            else:
                writer.writeStartDocument(version)
        elif token == QXmlStreamReader.EndDocument:
            writer.writeEndDocument()
        elif token == QXmlStreamReader.StartElement:
            namespaceDeclarations = reader.namespaceDeclarations()
            for namespaceDeclaration in namespaceDeclarations:
                writer.writeNamespace(namespaceDeclaration.namespaceUri(), namespaceDeclaration.prefix())
            writer.writeStartElement(reader.namespaceUri(), reader.name())
            writer.writeAttributes(reader.attributes())
        elif token == QXmlStreamReader.EndElement:
            writer.writeEndElement()
        elif token == QXmlStreamReader.Characters:
            if reader.isCDATA():
                writer.writeCDATA(reader.text())
            else:
                writer.writeCharacters(reader.text())
        elif token == QXmlStreamReader.Comment:
            writer.writeComment(reader.text())
        elif token == QXmlStreamReader.DTD:
            writer.writeDTD(reader.dtdName(), reader.dtdSystemId(), reader.dtdPublicId())
        elif token == QXmlStreamReader.EntityReference:
            print("QXmlStreamReader.EntityReference")
        elif token == QXmlStreamReader.ProcessingInstruction:
           writer.writeProcessingInstruction(reader.processingInstructionTarget(), reader.processingInstructionData())
        if reader.atEnd():
            break

    if reader.hasError():
        QMessageBox.critical(qApp.activeWindow(), "Stream read error", reader.errorString())
        return;

class MainWindow(DemoMainWindow):
    def __init__(self):
        DemoMainWindow.__init__(self, "QtitanFastInfoset", getFastInfosetVersion(), "FastInfoset/XML Converter")
        self.formUI = ui()
        panel = QWidget(self)
        self.formUI.setupUi(panel)
        self.highlighter = XmlSyntaxHighlighter(self.formUI.xmlEdit.document())

        self.connect(self.formUI.loadXML, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("loadXML()"))
        self.connect(self.formUI.loadFastInfoset, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("loadFastInfoset()"))
        self.connect(self.formUI.saveXML, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("saveAsXML()"))
        self.connect(self.formUI.saveFastInfoset, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("saveAsFastInfoset()"))
        self.setDemoWidget(panel, None, Qt.AlignTop, False)

    def loadXML(self):
        format = "XML (*.xml)"
        fileName = QFileDialog.getOpenFileName(self, "Open XML File", QDir.currentPath(), format)[0]
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QIODevice.ReadOnly):
            QMessageBox.critical(self, "File open error", file.errorString())
            return
        xmlreader = XmlStreamReader(file)

        text = QByteArray()
        buffer = QBuffer(text)
        buffer.open(QIODevice.WriteOnly)
        xmlwriter = XmlStreamWriter(buffer)
        xml_converter(xmlreader, xmlwriter)
        buffer.close()
        self.formUI.xmlEdit.setPlainText(QTextStream(text).readAll())

    def loadFastInfoset(self):
        format = "FastInfoset (*.fi)"
        fileName = QFileDialog.getOpenFileName(self, "Open FastInfoset File", QDir.currentPath(), format)[0]
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QIODevice.ReadOnly):
            QMessageBox.critical(self, "File open error", file.errorString())
            return

        xmlreader = FastInfosetStreamReader(file)
        text = QByteArray()
        buffer = QBuffer(text)
        buffer.open(QIODevice.WriteOnly)
        xmlwriter = XmlStreamWriter(buffer)
        xml_converter(xmlreader, xmlwriter)
        buffer.close()
        self.formUI.xmlEdit.setPlainText(QTextStream(text).readAll())

    def saveAsXML(self):
        format = "XML (*.xml)"
        fileName = QFileDialog.getSaveFileName(self, "Save As XML File", QDir.currentPath(), format)[0]
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QIODevice.WriteOnly):
            QMessageBox.critical(self, "File open error", file.errorString())
            return

        text = QByteArray(self.formUI.xmlEdit.toPlainText().encode())
        buffer = QBuffer(text)
        buffer.open(QIODevice.ReadOnly)
        xmlreader = XmlStreamReader(buffer)
        xmlwriter = XmlStreamWriter(file)
        xml_converter(xmlreader, xmlwriter)
        buffer.close()

    def saveAsFastInfoset(self):
        format = "FastInfoset (*.fi)"
        fileName = QFileDialog.getSaveFileName(self, "Save As FastInfoset File", QDir.currentPath(), format)[0]
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QIODevice.WriteOnly):
            QMessageBox.critical(self, "File open error", file.errorString())
            return

        text = QByteArray(self.formUI.xmlEdit.toPlainText().encode())
        buffer = QBuffer(text)
        buffer.open(QIODevice.ReadOnly)
        xmlreader = XmlStreamReader(buffer)
        xmlwriter = FastInfosetStreamWriter(file)
        xml_converter(xmlreader, xmlwriter)
        buffer.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setApplicationName("FastInfoset/XML Converter")
    app.setOrganizationName("Developer Machines")
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())