def got_allowed_kf_services_handler(self, reply): if reply.error() == QNetworkReply.NoError: allowed_kf_services = {} allowed_kf_services['any_type'] = {'services': []} xml = str(reply.readAll()) doc = QtXml.QDomDocument() doc.setContent(xml) service_types = doc.documentElement().childNodes() i = 0 while i<service_types.count(): service_type = service_types.at(i) service_type_name= service_type.nodeName() allowed_kf_services[service_type_name] = {'services': []} services = service_type.childNodes() j = 0 while j<services.count(): service = services.at(j) service_name = service.nodeName() allowed_kf_services[service_type_name]['services'].append(service_name) allowed_kf_services['any_type']['services'].append(service_name) j = j + 1 i = i + 1 self.allowed_kf_services = allowed_kf_services self.debug_write_allowed_services() self.get_kf_qlr_file() else: self.report_network_error("allowed services" + reply.errorString())
def SaveXml(self, xmlFile): domDoc = QtXml.QDomDocument() rootElem = self._SaveNode(None, self.root_, domDoc) domDoc.appendChild(rootElem) f = open(xmlFile, "w") f.write(domDoc.toString()) f.close()
def populateTable(self,filePath): self.filePath = filePath ui = self table = ui.tableWidget # table.clear() table.setRowCount(0) xml = file(filePath).read() d = QtXml.QDomDocument() d.setContent(xml) maps = d.elementsByTagName("maplayer") self.maps=maps for i in range(maps.length()): table.setRowCount(table.rowCount()+1) info = getMapInfo(maps.item(i)) nameItem = QTableWidgetItem(info['name']) nameItem.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled) nameItem.setCheckState(QtCore.Qt.Unchecked) nameItem.setData(QtCore.Qt.UserRole,str(i)) table.setItem(i,0,nameItem) table.setItem(i,1,FixedWidgetItem(info['mtype'])) table.setItem(i,2,FixedWidgetItem(info['geom'])) table.setItem(i,3,FixedWidgetItem(info['provider'])) ds = FixedWidgetItem(info['ds']) ds.setData(QtCore.Qt.ToolTipRole,info['ds']) table.setItem(i,4,ds)
def readProject(self, path): # validate project project_file = os.path.join(path, "project.xml") if os.path.exists(project_file) is False: return False dom_document = QtXml.QDomDocument() file = open(os.path.join(path, "project.xml"), "r") dom_document.setContent(file.read()) file.close() data = {} elements = dom_document.documentElement() node = elements.firstChild() while node.isNull() is False: tag = node.toElement() name = tag.tagName() data["Version"] = tag.attribute("Version") data["Type"] = tag.attribute("Type") data["Name"] = tag.attribute("Name") data["MainScript"] = tag.attribute("MainScript") node = node.nextSibling() if name != "pcode_project": return False else: return name, data
def create_qgis_template_output(output_path, composition): """Produce QGIS Template output. :param output_path: The output path. :type output_path: str :param composition: QGIS Composition object to get template. values :type composition: qgis.core.QgsComposition :return: Generated output path. :rtype: str """ # make sure directory is created dirname = os.path.dirname(output_path) if not os.path.exists(dirname): os.makedirs(dirname) template_document = QtXml.QDomDocument() element = template_document.createElement('Composer') composition.writeXML(element, template_document) template_document.appendChild(element) with open(output_path, 'w') as f: f.write(template_document.toByteArray()) return output_path
def save(self, filename): document = QtXml.QDomDocument() root = document.createElement('book') document.appendChild(root) root.setAttribute('title', self.title) root.setAttribute('overwrite', 'true' if self.overwrite else 'false') root.setAttribute('device', self.device) root.setAttribute('imageFlags', self.imageFlags) root.setAttribute('outputFormat', self.outputFormat) for filenameImg in self.images: itemImg = document.createElement('image') root.appendChild(itemImg) itemImg.setAttribute('filename', filenameImg) textXml = document.toString(4).toUtf8() try: fileXml = open(unicode(filename), 'w') fileXml.write(textXml) fileXml.close() except IOError: raise RuntimeError('Cannot create book file %s' % filename) self.filename = filename self.modified = False
def loadUseData(self): dom_document = QtXml.QDomDocument() file = open(self.appPathDict["usedata"], "r") dom_document.setContent(file.read()) file.close() elements = dom_document.documentElement() node = elements.firstChild() settingsList = [] while node.isNull() is False: property = node.toElement() sub_node = property.firstChild() while sub_node.isNull() is False: sub_prop = sub_node.toElement() if node.nodeName() == "openedprojects": path = sub_prop.text() if os.path.exists(path): self.OPENED_PROJECTS.append(path) elif node.nodeName() == "settings": settingsList.append((tuple(sub_prop.text().split('=', 1)))) sub_node = sub_node.nextSibling() node = node.nextSibling() self.SETTINGS.update(dict(settingsList)) self.loadKeymap()
def loadKeymap(self): if self.settings["firstRun"] == "True": self.CUSTOM_DEFAULT_SHORTCUTS = self.DEFAULT_SHORTCUTS return dom_document = QtXml.QDomDocument() file = open(self.appPathDict["keymap"], "r") x = dom_document.setContent(file.read()) file.close() elements = dom_document.documentElement() node = elements.firstChild() while node.isNull() is False: property = node.toElement() sub_node = property.firstChild() group = node.nodeName() while sub_node.isNull() is False: sub_prop = sub_node.toElement() tag = sub_prop.toElement() name = tag.tagName() shortcut = tag.attribute("shortcut") shortcut = QtGui.QKeySequence(shortcut).toString() function = tag.attribute("function") self.CUSTOM_DEFAULT_SHORTCUTS[group][name] = [ shortcut, function ] sub_node = sub_node.nextSibling() node = node.nextSibling()
def readHFile(self, device): """ Обработка с услугами """ doc = QtXml.QDomDocument() doc.setContent(device) root = doc.documentElement() if root.tagName() != u'ZL_LIST': self.err2log(u'Некорректная структура H-файла.') return False if not self.checkVersion(root): self.err2log(u'Некорректная версия обмена в H-файле.') return False zglv = root.firstChildElement('ZGLV') self.date = QtCore.QDate.fromString( zglv.firstChildElement('DATA').text(), QtCore.Qt.ISODate) if not self.date.isValid(): self.date = QtCore.QDate.currentDate() self.accountIdSet = set() zap = root.firstChildElement('ZAP') while not zap.isNull(): QtGui.qApp.processEvents() self.processZap(zap) zap = zap.nextSiblingElement('ZAP') updateAccounts(self.accountIdSet) return 0
def get_allowed_kf_services(self): allowed_kf_services = {} allowed_kf_services['any_type'] = {'services': []} url_to_get = self.replace_variables(KF_SERVICES_URL) response = urlopen(url_to_get) xml = response.read() doc = QtXml.QDomDocument() doc.setContent(xml) service_types = doc.documentElement().childNodes() i = 0 while i < service_types.count(): service_type = service_types.at(i) service_type_name = service_type.nodeName() allowed_kf_services[service_type_name] = {'services': []} services = service_type.childNodes() j = 0 while j < services.count(): service = services.at(j) service_name = service.nodeName() allowed_kf_services[service_type_name]['services'].append( service_name) allowed_kf_services['any_type']['services'].append( service_name) j = j + 1 i = i + 1 return allowed_kf_services
def __init__(self, parent=None): super(TreeWidget, self).__init__(parent) self.setAcceptDrops(True) #self.setDragEnabled(True) self.setDragDropMode(QAbstractItemView.InternalMove) self.setObjectName("treeWidget") self.setMinimumSize(QtCore.QSize(170, 425)) self.setMaximumSize(QtCore.QSize(170, 65525)) self.setGeometry(QtCore.QRect(10, 135, 170, 425)) self.header().setResizeMode(QtGui.QHeaderView.Stretch) self.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.header().setResizeMode(QHeaderView.ResizeToContents) self.header().setStretchLastSection(False) self.header().hide() self.setHeaderLabels([""]) self.setExpandsOnDoubleClick(True) self.domDocument = QtXml.QDomDocument() self.domElementForItem = {} self.folderIcon = QtGui.QIcon() self.bookmarkIcon = QtGui.QIcon() self.folderIcon.addPixmap( self.style().standardPixmap(QtGui.QStyle.SP_DirClosedIcon), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.folderIcon.addPixmap( self.style().standardPixmap(QtGui.QStyle.SP_DirOpenIcon), QtGui.QIcon.Normal, QtGui.QIcon.On) self.bookmarkIcon.addPixmap(self.style().standardPixmap( QtGui.QStyle.SP_FileIcon))
def _xmlMerge(self, path): """Merges all edf-xml files in the given directory into a temporary file Args: ----- path: str path to the Elmer xml-files configuration files """ # create a temporary file mybuf = tempfile.TemporaryFile() gen_file = path + "edf.xml" # general settings first = et.parse(gen_file).getroot() # solver settings xml_files = glob.glob(path + "*.xml") xml_files = [file for file in xml_files if not os.path.basename(file).startswith("edf")] xml_files = [file for file in xml_files if not os.path.basename(file).startswith("eg")] for xml_file in xml_files: data = et.parse(xml_file).getroot() first.extend(data) mybuf.write(et.tostring(first)) mybuf.seek(0) temp = mybuf.read().decode() mybuf.close() self._elmerDefs = QtXml.QDomDocument() self._elmerDefs.setContent(temp)
def load(self, filename): try: fileXml = open(unicode(filename), 'r') textXml = fileXml.read() fileXml.close() except IOError: raise RuntimeError('Cannot open book file %s' % filename) document = QtXml.QDomDocument() if not document.setContent(QtCore.QString.fromUtf8(textXml)): raise RuntimeError('Error parsing book file %s' % filename) root = document.documentElement() if root.tagName() != 'book': raise RuntimeError('Unexpected book format in file %s' % filename) self.title = root.attribute('title', 'Untitled') self.overwrite = root.attribute('overwrite', 'true' if Book.DefaultOverwrite else 'false') == 'true' self.device = root.attribute('device', Book.DefaultDevice) self.outputFormat = root.attribute('outputFormat', Book.DefaultOutputFormat) self.imageFlags = int(root.attribute('imageFlags', str(Book.DefaultImageFlags))) self.filename = filename self.modified = False self.images = [] items = root.elementsByTagName('image') if items is None: return for i in xrange(0, len(items)): item = items.at(i).toElement() if item.hasAttribute('filename'): self.images.append(item.attribute('filename'))
def serialize(self, rootNode): doc = QtXml.QDomDocument() xmlNode = self.xmlFromNode(doc, rootNode) doc.appendChild(xmlNode) for child in rootNode._children: self._recurseXml(doc, xmlNode, child) return doc.toString(indent=4)
def load(self): file = QtCore.QFile(self.libMgr.getConfigFile()) #Load data into config, if file doesn't exist, create one if (not file.open(QtCore.QIODevice.ReadWrite | QtCore.QIODevice.Text)): print 'config.ini could not be opened' return self.config = QtXml.QDomDocument("ConfigFile") #Validate file xml if (not self.config.setContent(file)): self.libMgr.printError('config.ini could not be parsed', "Config load failed", 10) return file.close() root = self.config.documentElement() #If there was wierdness as the root node, error if (root.tagName() != 'config' and root.tagName() != ''): self.libMgr.printError('config.ini invalid xml', "Config load failed", 10) return #If there was no root, empty file, start one elif (root.tagName() == ''): self.__initDefaults() #If its good, make sure all the base nodes have not been manually deleted else: self.__validateDefaults(root) self.save()
def _getExtent(self, layer): def getTargetWindow(): nodes = doc.elementsByTagName('TargetWindow') node = nodes.item(0) targetWindow = {'ulX': None, 'ulY': None, 'lrX': None, 'lrY': None} labels = { 'UpperLeftX': 'ulX', 'UpperLeftY': 'ulY', 'LowerRightX': 'lrX', 'LowerRightY': 'lrY' } for key, value in labels.iteritems(): text = node.firstChildElement(key).text() if len(text) == 0: continue targetWindow[value] = float(text) return targetWindow doc = QtXml.QDomDocument() file = QtCore.QFile(layer.source()) doc.setContent(file) file.close() tw = getTargetWindow() return QgsCore.QgsRectangle(tw['ulX'], tw['lrY'], tw['lrX'], tw['ulY'])
def renderTemplate(self, theTemplateFilePath, theOutputFilePath): """Load a QgsComposer map from a template and render it .. note:: THIS METHOD IS EXPERIMENTAL AND CURRENTLY NON FUNCTIONAL Args: theTemplateFilePath - path to the template that should be loaded. theOutputFilePath - path for the output pdf Returns: None Raises: None """ self.setupComposition() myResolution = self.composition.printResolution() self.printer = setupPrinter(theOutputFilePath, theResolution=myResolution) if self.composition: myFile = QtCore.QFile(theTemplateFilePath) myDocument = QtXml.QDomDocument() myDocument.setContent(myFile, False) # .. todo:: fix magic param myNodeList = myDocument.elementsByTagName('Composer') if myNodeList.size() > 0: myElement = myNodeList.at(0).toElement() self.composition.readXML(myElement, myDocument) self.printToPdf(theOutputFilePath)
def _capabilitiesRequestFinished(self): # Receive the server capabilities XML if self._theReply.error() == 1: QMessageBox.information( None, '', QApplication.translate( "QgsWpsGui", "Connection Refused. Please check your Proxy-Settings")) pass xmlString = self._theReply.readAll().data() self._theReply.deleteLater() self.doc = QtXml.QDomDocument() self.doc.setContent(xmlString, True) root = self.doc.documentElement() version = root.attribute("version") if version != "1.0.0": QMessageBox.information( None, QApplication.translate("QgsWps", "Only WPS Version 1.0.0 is supported"), xmlString) pass self.capabilitiesRequestFinished.emit()
def saveKeymap(self, path=None): dom_document = QtXml.QDomDocument("keymap") keymap = dom_document.createElement("keymap") dom_document.appendChild(keymap) for key, value in self.useData.CUSTOM_SHORTCUTS.items(): root = dom_document.createElement(key) keymap.appendChild(root) for short, func in value.items(): tag = dom_document.createElement(short) if key == "Editor": shortName = func[0] keyValue = str(func[1]) tag.setAttribute("shortcut", shortName) tag.setAttribute("value", keyValue) else: tag.setAttribute("shortcut", func) root.appendChild(tag) if path is None: path = self.useData.appPathDict["keymap"] file = open(path, "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close()
def getHtml(self): """ HTML output, used to print the list """ while (self.canFetchMore()): self.fetchMore() htmlDocument = QtXml.QDomDocument("list") html = htmlDocument.createElement("html") htmlDocument.appendChild(html) body = htmlDocument.createElement("body") html.appendChild(body) table = htmlDocument.createElement("table") table.setAttribute("style", "border: 1px solid black") table.setAttribute("border", "none") body.appendChild(table) for i in range(0, self.rowCount()): row = htmlDocument.createElement("tr") data = htmlDocument.createElement("td") piggeonId = self.index(i, 1).data().toString() piggeonId += "-" piggeonId += self.index(i, 2).data().toString() piggeonId += "-" piggeonId += self.index(i, 3).data().toString() text = htmlDocument.createTextNode(piggeonId) data.appendChild(text) row.appendChild(data) for j in range(4, 10): data = htmlDocument.createElement("td") text = htmlDocument.createTextNode( self.index(i, j).data().toString()) data.appendChild(text) row.appendChild(data) table.appendChild(row) # fichero = file ("/tmp/fichero.html", "w") # fichero.write (htmlDocument.toString ()) # fichero.close () return htmlDocument.toString()
def loadModulesForCompletion(self): dom_document = QtXml.QDomDocument() try: file = open(self.appPathDict["modules"], "r") dom_document.setContent(file.read()) file.close() except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) return element = dom_document.documentElement() node = element.firstChild() self.libraryDict = {} while node.isNull() is False: property = node.toElement() sub_node = property.firstChild() moduleName = node.nodeName() use = property.attribute('use') itemList = [] while sub_node.isNull() is False: sub_prop = sub_node.toElement() itemList.append(sub_prop.text()) sub_node = sub_node.nextSibling() self.libraryDict[moduleName] = [itemList, use] node = node.nextSibling()
def saveModulesForCompletion(self): dom_document = QtXml.QDomDocument("modules") modules = dom_document.createElement("modules") dom_document.appendChild(modules) for i, v in self.libraryDict.items(): tag = dom_document.createElement(i) modules.appendChild(tag) tag.setAttribute("use", str(v[1])) for subModule in v[0]: item = dom_document.createElement("item") tag.appendChild(item) t = dom_document.createTextNode(subModule) item.appendChild(t) try: file = open(self.appPathDict["modules"], "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close() except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
def load(self): dom_document = QtXml.QDomDocument() file = open(self.projectPathDict["buildprofile"], "r") dom_document.setContent(file.read()) file.close() dataDict = {} elements = dom_document.documentElement() node = elements.firstChild() while node.isNull() is False: name = node.nodeName() expandedName = name.replace('-', ' ') if expandedName in self.lists: sub_node = node.firstChild() while sub_node.isNull() is False: sub_prop = sub_node.toElement() self.lists[expandedName].append(sub_prop.text()) sub_node = sub_node.nextSibling() dataDict[expandedName] = self.lists[expandedName] else: sub_prop = node.toElement() dataDict[name] = sub_prop.text() node = node.nextSibling() return dataDict
def load_defaults(self, filename=DefaultsXML): try: fileXml = open(unicode(filename), 'r') textXml = fileXml.read() fileXml.close() except IOError: self.device = Book.DefaultDevice self.overwrite = Book.DefaultOverwrite self.imageFlags = Book.DefaultImageFlags self.cbz = Book.DefaultCBZ self.save_defaults(filename) return document = QtXml.QDomDocument() if not document.setContent(QtCore.QString.fromUtf8(textXml)): raise RuntimeError('Error parsing defaults file %s' % filename) root = document.documentElement() if root.tagName() != 'defaults': raise RuntimeError('Unexpected defaults format in file %s' % filename) self.overwrite = root.attribute( 'overwrite', 'true' if Book.DefaultOverwrite else 'false') == 'true' self.device = root.attribute('device', Book.DefaultDevice) orient = root.attribute( 'orientImages', 'true' if Book.DefaultImageFlags & ImageFlags.Orient else 'false') == 'true' split = root.attribute( 'splitImages', 'true' if Book.DefaultImageFlags & ImageFlags.Split else 'false') == 'true' shrink = root.attribute( 'shrinkImages', 'true' if Book.DefaultImageFlags & ImageFlags.Shrink else 'false') == 'true' enlarge = root.attribute( 'enlargeImages', 'true' if Book.DefaultImageFlags & ImageFlags.Enlarge else 'false') == 'true' frame = root.attribute( 'frameImages', 'true' if Book.DefaultImageFlags & ImageFlags.Frame else 'false') == 'true' dither = root.attribute( 'ditherImages', 'true' if Book.DefaultImageFlags & ImageFlags.Quantize else 'false') == 'true' rtl = root.attribute( 'rightToLeft', 'true' if Book.DefaultImageFlags & ImageFlags.RightToLeft else 'false') == 'true' self.imageFlags = ((ImageFlags.Orient if orient else 0) | (ImageFlags.Split if split else 0) | (ImageFlags.Shrink if shrink else 0) | (ImageFlags.Enlarge if enlarge else 0) | (ImageFlags.Frame if frame else 0) | (ImageFlags.Quantize if dither else 0) | (ImageFlags.RightToLeft if rtl else 0)) self.cbz = root.attribute( 'cbz', 'true' if Book.DefaultCBZ else 'false') == 'true'
def save(self, name=None): # save style dom_document = QtXml.QDomDocument("Scheme") main = dom_document.createElement("Attributes") dom_document.appendChild(main) root = dom_document.createElement("lexer") main.appendChild(root) for key, value in self.lexerStyler.currentStyle.items(): tag = dom_document.createElement("property") tag.setAttribute("font", value[0]) tag.setAttribute("color", value[1]) tag.setAttribute("size", value[2]) tag.setAttribute("bold", str(value[3])) tag.setAttribute("italic", str(value[4])) tag.setAttribute("paper", value[5]) t = dom_document.createTextNode(key) tag.appendChild(t) root.appendChild(tag) root = dom_document.createElement("editor") main.appendChild(root) for key, value in self.editorStyler.currentProperties.items(): tag = dom_document.createElement("property") root.appendChild(tag) tag.setAttribute("background", value[0]) tag.setAttribute("foreground", value[1]) if key == "Calltips": tag.setAttribute("highLight", value[2]) if key == "Number Margin": tag.setAttribute("font", value[2]) tag.setAttribute("size", str(value[3])) tag.setAttribute("bold", str(value[4])) tag.setAttribute("italic", str(value[5])) t = dom_document.createTextNode(key) tag.appendChild(t) if name is None: name = self.schemeNameBox.currentText() groupName = self.schemeTypeBox.currentText() path = os.path.join( self.useData.appPathDict["stylesdir"], groupName, name + '.xml') try: file = open(path, "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close() except Exception as err: message = QtGui.QMessageBox.warning(self, "Save", "Saving failed: {0}".format(str(err))) file.close() return self.loadSchemeNames()
def save(self): fileName = self.pathDict["ropeprofile"] dom_document = QtXml.QDomDocument("rope_profile") main_data = dom_document.createElement("rope") dom_document.appendChild(main_data) root = dom_document.createElement("ignoresyntaxerrors") attrib = dom_document.createTextNode( self.ignoreSyntaxErrorsBox.currentText()) root.appendChild(attrib) main_data.appendChild(root) root = dom_document.createElement("ignorebadimports") attrib = dom_document.createTextNode( self.ignoreBadImportsBox.currentText()) root.appendChild(attrib) main_data.appendChild(root) root = dom_document.createElement("maxhistoryitems") attrib = dom_document.createTextNode(str(self.maxHistoryBox.value())) root.appendChild(attrib) main_data.appendChild(root) root = dom_document.createElement("Extensions") main_data.appendChild(root) defExt = ['*.py', '*.pyw'] for i in defExt: tag = dom_document.createElement("item") root.appendChild(tag) t = dom_document.createTextNode(i) tag.appendChild(t) root = dom_document.createElement("IgnoredResources") main_data.appendChild(root) defIgnore = [ "*.pyc", "*~", ".ropeproject", ".hg", ".svn", "_svn", ".git", "__pycache__" ] for i in defIgnore: tag = dom_document.createElement("item") root.appendChild(tag) t = dom_document.createTextNode(i) tag.appendChild(t) root = dom_document.createElement("CustomFolders") main_data.appendChild(root) file = open(fileName, "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close()
def editComment(self): edit = EditComment(self.commentViewer.toPlainText(), self) edit.exec_() if edit.accepted: comment = edit.commentEdit.toPlainText() source = self.sourceLine.text() snippetName = self.currentSnippetNameLabel.text() path = os.path.join(self.useData.appPathDict["librarydir"], snippetName) dom_document = QtXml.QDomDocument() file = open(path, "r") dom_document.setContent(file.read()) file.close() # save changes dom_document = QtXml.QDomDocument("snippet") root = dom_document.createElement("snippet") dom_document.appendChild(root) tag = dom_document.createElement('comments') root.appendChild(tag) t = dom_document.createCDATASection(comment) tag.appendChild(t) tag = dom_document.createElement('source') root.appendChild(tag) t = dom_document.createCDATASection(source) tag.appendChild(t) tag = dom_document.createElement('code') root.appendChild(tag) t = dom_document.createCDATASection(self.codeViewer.text()) tag.appendChild(t) file = open(path, "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close() self.viewLibraryItem(self.currentSnippetItem)
def writeDefaultSession(self): dom_document = QtXml.QDomDocument("session") session = dom_document.createElement("session") dom_document.appendChild(session) file = open(os.path.join(self.projectPath, "Data", "session.xml"), "w") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(dom_document.toString()) file.close()
def deserialize(self, xmlString): xml = QtXml.QDomDocument() if not xml.setContent(xmlString): print("failed") raise ValueError() xmlRootNode = xml.documentElement() rootNode = self.nodeFromXml(xmlRootNode) self.build_tree(xmlRootNode, rootNode) return rootNode
def loadProjectData(self): dom_document = QtXml.QDomDocument() file = open(os.path.join(self.pathDict[ "root"], "Data", "projectdata.xml"), "r") x = dom_document.setContent(file.read()) file.close() elements = dom_document.documentElement() node = elements.firstChild() shortcuts = [] recentfiles = [] favourites = [] launchers = {} settingsList = [] while node.isNull() is False: property = node.toElement() sub_node = property.firstChild() while sub_node.isNull() is False: sub_prop = sub_node.toElement() if node.nodeName() == "shortcuts": shortcuts.append(sub_prop.text()) elif node.nodeName() == "recentfiles": if os.path.exists(sub_prop.text()): recentfiles.append(sub_prop.text()) else: pass elif node.nodeName() == "favourites": favourites.append(sub_prop.text()) elif node.nodeName() == "settings": settingsList.append((tuple(sub_prop.text().split('=', 1)))) elif node.nodeName() == "launchers": tag = sub_prop.toElement() path = tag.attribute("path") param = tag.attribute("param") launchers[path] = param sub_node = sub_node.nextSibling() node = node.nextSibling() settingsDict = dict(settingsList) settingsDict['LastCloseSuccessful'] = settingsDict['Closed'] settingsDict['Closed'] = "False" settingsDict['venvdir'] = self.useData.appPathDict['venvdir'] self.PROJECT_DATA = {} self.PROJECT_DATA["shortcuts"] = shortcuts self.PROJECT_DATA["favourites"] = favourites self.PROJECT_DATA["recentfiles"] = recentfiles self.PROJECT_DATA["settings"] = settingsDict self.PROJECT_DATA["launchers"] = launchers self.pathDict["DefaultVenv"] = settingsDict["DefaultVenv"] # in order that a crash can be reported self.saveProjectData()