def get_searchable_content(self): """ Pulls out tags from the object and returns them in order to be used by the filtered() method. """ f = QFile(self.fileinfo.absoluteFilePath()) f.open(QIODevice.ReadOnly) #stream = QTextStream(f) #stream.setCodec("UTF-8") try: doc = QDomDocument() doc.setContent( f.readAll() ) docelt = doc.documentElement() texts = [] for tagName in FileSystemItem.xmlSearchableTags: nodes = docelt.elementsByTagName(tagName) for i in range(nodes.count()): node = nodes.at(i) value = node.firstChild().toText().data() #print value texts.append( value ) # Add keywords nodes = docelt.elementsByTagName("keywordList") for i in range(nodes.count()): kwnode = nodes.at(i) valnodes = kwnode.toElement().elementsByTagName("value") for j in range(valnodes.count()): value = valnodes.at(j).firstChild().toText().data() texts.append(value) return u' '.join(texts) finally: f.close()
def on_pushButton_5_clicked(self): self.listWidget.clear() # 先清空显示 file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if (not status): file.close() raise Exception(str(rrorMsg)) file.close() docElem = doc.documentElement() # 返回根元素 n = docElem.firstChild() while (not n.isNull()): if (n.isElement()): e = n.toElement() self.listWidget.addItem(e.tagName() + e.attribute(QString("编号"))) list = e.childNodes() for i in range(list.count()): node = list.at(i) if (node.isElement()): self.listWidget.addItem(" " + node.toElement().tagName() + " : " + node.toElement().text()) n = n.nextSibling()
def get_template_element(self, path): """ Gets the template element. :param path: The path of the template :type path: String :return: QDomDocument, QDomDocument.documentElement() :rtype: Tuple """ config_file = os.path.join(path) config_file = QFile(config_file) if not config_file.open(QIODevice.ReadOnly): template = os.path.basename(path) self.prog.setLabelText( QApplication.translate('TemplateUpdater', 'Failed to update {}'.format(template))) error_title = QApplication.translate('TemplateContentReader', 'File Reading Error') error_message = QApplication.translate( 'TemplateContentReader', 'Failed to update {0}. ' 'Check the file permission of {0}'.format(template)) QMessageBox.critical(iface.mainWindow(), error_title, error_message) return None doc = QDomDocument() status, msg, line, col = doc.setContent(config_file) if not status: return None doc_element = doc.documentElement() return doc_element
def getActivePlugins(self, filename=None): ''' Function checks xml and returns if plugin was active on previous program execution xmlfile: specifies alternative path to xml file with plugin information ''' if not filename: filename = self.xmlFile if os.path.exists(filename): fileObject = QFile(filename) Xml = QDomDocument("xmldoc") Xml.clear() if (fileObject.open(QIODevice.ReadOnly)): Xml.setContent(fileObject.readAll()) fileObject.close() rootNode = Xml.documentElement() nodeList = rootNode.elementsByTagName("plugin") for i in range(nodeList.length()): bpNode = nodeList.at(i).toElement() path = str(bpNode.attribute("path")) if path in self.pluginActions: self.pluginActions[path].setLoaded( bpNode.attribute("active") == "y") else: logging.warning( "No plugin for %s found, maybe it was moved/deleted?", path)
def parse_knitting_symbol(symbolPath): """ Parse the knitting symbol located at path symbolPath. """ descriptionFile = QFile(symbolPath + "/description") if (not descriptionFile.exists()) or descriptionFile.error(): return None # parse XML dom = QDomDocument() (status, msg, line, col) = dom.setContent(descriptionFile) if not status: errorMessage = ("Failed reading pattern description in file %s -- " "%s at line %d column %d" % (descriptionFile.fileName(), msg, line, col)) logger.error(errorMessage) return None # make sure we're reading a sconcho pattern description root = dom.documentElement() if root.tagName() != "sconcho": return None # parse the actual content node = root.firstChild() if node.toElement().tagName() != "knittingSymbol": return None content = parse_symbol_description(node) # add the absolute path content["svgPath"] = symbolPath + "/" + content["svgName"] + ".svg" return content
def getActivePlugins(self, filename=None): ''' Function checks xml and returns if plugin was active on previous program execution xmlfile: specifies alternative path to xml file with plugin information ''' if not filename: filename = self.xmlFile if os.path.exists(filename): fileObject = QFile(filename) Xml = QDomDocument("xmldoc") Xml.clear() if (fileObject.open(QIODevice.ReadOnly)): Xml.setContent(fileObject.readAll()) fileObject.close() rootNode = Xml.documentElement() nodeList = rootNode.elementsByTagName("plugin") for i in range(nodeList.length()): bpNode = nodeList.at(i).toElement() path = str(bpNode.attribute("path")) if path in self.pluginActions: self.pluginActions[path].setLoaded(bpNode.attribute("active") == "y") else: logging.warning("No plugin for %s found, maybe it was moved/deleted?", path)
def load(self, filename): f = QFile(filename) f.open(QIODevice.ReadOnly) doc = QDomDocument() doc.setContent(f) root = doc.documentElement() items = root.childNodes().at(0).toElement() connections = root.childNodes().at(1).toElement() itemmap = dict() # Iterate through all children for n in [ items.childNodes().at(i).toElement() for i in range(items.childNodes().length()) ]: # type and pos _type = str(n.attributeNode("type").value()) poselem = n.elementsByTagName("pos").at(0).toElement() _pos = QPointF(float(str(poselem.attributeNode("x").value())), float(str(poselem.attributeNode("y").value()))) exec("from items.%s import *" % _type) item = eval(_type)() item.setPos(_pos) self.addItem(item) item.load(n.elementsByTagName("properties").at(0).toElement()) itemmap[int(str(n.attributeNode("id").value()))] = item # Connections for n in [ connections.childNodes().at(i).toElement() for i in range(connections.childNodes().length()) ]: sourceelem = n.childNodes().at(0).toElement() targetelem = n.childNodes().at(1).toElement() sourceid = int(str(sourceelem.attributeNode("id").value())) sourceport = int(str(sourceelem.attributeNode("port").value())) targetid = int(str(targetelem.attributeNode("id").value())) targetport = int(str(targetelem.attributeNode("port").value())) self.graph.addEdge(itemmap[sourceid].providesPorts[sourceport], itemmap[targetid].requiresPorts[targetport]) QApplication.processEvents() self.update() QApplication.processEvents() for item in self.graph.items(): self.graph.updateEdges(item) f.close() self.setModified(False)
def stringToColorRamp( self, rampdef ): try: if '<' not in rampdef: return None d=QDomDocument() d.setContent(rampdef) return QgsSymbolLayerV2Utils.loadColorRamp( d.documentElement() ) except: return None
def __handleReply(self, reply) : self.activeQuery = "" if reply.error() != QNetworkReply.NoError : print(">>>>>>>> ERROR! : Network Error (" + reply.errorString() + ")") self.__notifications = -1 self.queryFailed.emit() return doc = QDomDocument() doc.setContent(reply) root = doc.documentElement() if root.tagName() == "error_response" : print(">>>>>>>> ERROR! : Facebook Server Returned Error ") err = root.firstChildElement("error_code").text() if int(err) == 190 : self.queryFailed.emit() self.__notifications = -1 self.authExpired.emit() print("\tError Code : " + err) print("\tError Message : " + root.firstChildElement("error_msg").text()) elif root.tagName() == "fql_query_response" : notificationList = root.elementsByTagName("notification") print("== Recived Query Result ==") print("\tTotal Notifications : " + str(notificationList.length())) for i in range(notificationList.length()) : notification = notificationList.at(i) print(unicode(notification.namedItem("title_html").toElement().text())) children = notification.namedItem("title_html").toElement().childNodes() print("title has " + str(children.length()) + " children") for j in range(children.length()) : print(notification.nodeType()) print(children.at(j).nodeName()) if (int(notification.namedItem("anon").toElement().text()) - int(notification.namedItem("created_time").toElement().text())) <= self.settings["pollinterval"] : print("\tNotification " + str(i) + " is New! Firing KNotification::event()") icon = QPixmap(self.settings["notification_icon"]) text = self.settings["notification_title"] text.replace("%title_html%", notification.namedItem("title_html").toElement().text()) KNotification.event(KNotification.Notification, "Facebook", text, icon) else : print(">>>>>>>> ERROR! : Facebook Server returned Unexpected Output : ") print(doc.toByteArray()) if notificationList.length() != self.__notifications : self.__notifications = notificationList.length() self.notificationsChanged.emit()
class StrongParser(): """ This class is used to load a strong lexicon in XML, parse it, and query infos. """ def __init__(self, lexicon="../lexicons/Strongs_EN/strongsgreek.xml"): "Takes the path to the lexicon as argument, or uses the default one." self._doc = QDomDocument() if not self._doc.setContent(QFile(lexicon)): print("ERROR: couldn't load lexicon. Please, try harder.'") self._entries = self._doc.documentElement()\ .namedItem("entries").childNodes() def getGreekUnicode(self, number): "Returns the greek lexical form in unicode for the given strong number." return self.getStrong(number).namedItem("greek")\ .toElement().attribute("unicode") def getStrong(self, number): """Returns a QDomNode for the given strong number. Used mainly internally.""" return self._entries.at(number - 1) def getDefinition(self, number): """Returns the word definition from the strong lexicon. Uses first the strong definition, and if not the KJV definition. """ s = self.getStrongDefinition(number) if not s: s = self.getKJVDefinition(number) return self.clean(s) def clean(self, s): "Used to clean some text: removes line breaks, and multiple spaces." s = s.replace("\n", " ") os = "" while s != os: os = s s = s.replace(" ", " ") return s.strip() def getStrongDefinition(self, number): "Returns the strong definition for the given strong number." return self.getStrong(number).namedItem("strongs_def")\ .toElement().text() def getKJVDefinition(self, number): "Returns the KJV definition for the given strong number." d = self.getStrong(number).namedItem("kjv_def").toElement().text() if d[:3] == ":--": d = d[3:] return self.clean(d)
def get_template_element(self, path): """ Gets the template element. :param path: The path of the template :type path: String :return: QDomDocument, QDomDocument.documentElement() :rtype: Tuple """ config_file = os.path.join(path) config_file = QFile(config_file) if not config_file.open(QIODevice.ReadOnly): template = os.path.basename(path) self.prog.setLabelText( QApplication.translate( 'TemplateUpdater', 'Failed to update {}'.format( template ) ) ) error_title = QApplication.translate( 'TemplateContentReader', 'File Reading Error' ) error_message = QApplication.translate( 'TemplateContentReader', 'Failed to update {0}. ' 'Check the file permission of {0}'.format( template ) ) QMessageBox.critical( iface.mainWindow(), error_title, error_message ) return None doc = QDomDocument() status, msg, line, col = doc.setContent( config_file ) if not status: return None doc_element = doc.documentElement() return doc_element
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != 'qgis_style': return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement('symbols') symbol_element = symbols_element.firstChildElement() while not symbol_element.isNull(): if symbol_element.tagName() == 'symbol': symbol = QgsSymbolLayerV2Utils.loadSymbol(symbol_element) if symbol: self._symbols.append({ 'name': symbol_element.attribute('name'), 'symbol': symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps self._colorramps = [] ramps_element = document_element.firstChildElement('colorramps') ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == 'colorramp': colorramp = QgsSymbolLayerV2Utils.loadColorRamp(ramp_element) if colorramp: self._colorramps.append({ 'name': ramp_element.attribute('name'), 'colorramp': colorramp }) ramp_element = ramp_element.nextSiblingElement() return True
def parse (self, xml=None): """ :param xml: XML to parse :type xml: QDomElement or str """ if isinstance (xml, QDomElement): return xml doc = QDomDocument() (ok, errorMsg, errorLine, errorCol) = doc.setContent(xml, True) if ok: return doc.documentElement() else: raise ValueError ("{} in line {}, column {}".format(errorMsg, errorLine, errorCol))
def _editTemplate(self, templatePath, newName): """ Updates the template document to use the new name. """ templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Open Operation Error"), \ "{0}\n{1}".format( QApplication.translate("TemplateDocumentSelector", "Cannot read template file."), \ templateFile.errorString() )) return (False, "") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerElement = templateDoc.documentElement() titleAttr = composerElement.attributeNode("_title") if not titleAttr.isNull(): titleAttr.setValue(newName) # Try remove file status = templateFile.remove() if not status: return (False, "") # Create new file newTemplatePath = self._composerTemplatesPath() + "/" + newName + ".sdt" newTemplateFile = QFile(newTemplatePath) if not newTemplateFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector", "Could not save template file."), \ newTemplateFile.errorString() )) return (False, "") if newTemplateFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Error"), \ QApplication.translate("TemplateDocumentSelector", "Could not save template file.")) return (False, "") newTemplateFile.close() return (True, newTemplatePath)
def parse(self, xml=None): """ :param xml: XML to parse :type xml: QDomElement or str """ if isinstance(xml, QDomElement): return xml doc = QDomDocument() (ok, errorMsg, errorLine, errorCol) = doc.setContent(xml, True) if ok: return doc.documentElement() else: raise ValueError("{} in line {}, column {}".format( errorMsg, errorLine, errorCol))
def on_pushButton_4_clicked(self): # 我们先清空显示,然后显示“无法添加!”,这样如果添加失败则会显示“无法添加!” self.listWidget.clear() self.listWidget.addItem(QString("无法添加!")) file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if not status: file.close() raise Exception(str(rrorMsg)) file.close() root = doc.documentElement() # 获取根元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() # 我们获得了最后一个孩子结点的编号,然后加1,便是新的编号 num = root.lastChild().toElement().attribute(QString("编号")) count = num.toInt() + 1 id.setValue(QString.number(count)) book.setAttributeNode(id) text = doc.createTextNode(self.lineEdit_2.text()) title.appendChild(text) text = doc.createTextNode(self.lineEdit_3.text()) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("file open Err") out = QTextStream(file) doc.save(out, 4) file.close() # 最后更改显示为“添加成功!” self.listWidget.clear() self.listWidget.addItem(QString("添加成功!"))
def _editTemplate(self,templatePath,newName): """ Updates the template document to use the new name. """ templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Open Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Cannot read template file."), \ templateFile.errorString() )) return (False,"") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerElement = templateDoc.documentElement() titleAttr = composerElement.attributeNode("_title") if not titleAttr.isNull(): titleAttr.setValue(newName) #Try remove file status = templateFile.remove() if not status: return (False,"") #Create new file newTemplatePath = self._composerTemplatesPath() + "/" + newName + ".sdt" newTemplateFile = QFile(newTemplatePath) if not newTemplateFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Could not save template file."), \ newTemplateFile.errorString() )) return (False,"") if newTemplateFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Error"), \ QApplication.translate("TemplateDocumentSelector","Could not save template file.")) return (False,"") newTemplateFile.close() return (True,newTemplatePath)
def __add_layer_definition_file(self, file_name, root_group): """ shamelessly copied from https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp """ qfile = QFile(file_name) if not qfile.open(QIODevice.ReadOnly): return None doc = QDomDocument() if not doc.setContent(qfile): return None file_info = QFileInfo(qfile) QDir.setCurrent(file_info.absoluteDir().path()) root = QgsLayerTreeGroup() ids = doc.elementsByTagName('id') for i in xrange(0, ids.size()): id_node = ids.at(i) id_elem = id_node.toElement() old_id = id_elem.text() layer_name = old_id[:-17] date_time = QDateTime.currentDateTime() new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz') id_elem.firstChild().setNodeValue(new_id) tree_layer_nodes = doc.elementsByTagName('layer-tree-layer') for j in xrange(0, tree_layer_nodes.count()): layer_node = tree_layer_nodes.at(j) layer_elem = layer_node.toElement() if old_id == layer_elem.attribute('id'): layer_node.toElement().setAttribute('id', new_id) layer_tree_elem = doc.documentElement().firstChildElement( 'layer-tree-group') load_in_legend = True if not layer_tree_elem.isNull(): root.readChildrenFromXML(layer_tree_elem) load_in_legend = False layers = QgsMapLayer.fromLayerDefinition(doc) QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend) nodes = root.children() for node in nodes: root.takeChild(node) del root root_group.insertChildNodes(-1, nodes) return None
def __add_layer_definition_file(self, file_name, root_group): """ shamelessly copied from https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp """ qfile = QFile(file_name) if not qfile.open(QIODevice.ReadOnly): return None doc = QDomDocument() if not doc.setContent(qfile): return None file_info = QFileInfo(qfile) QDir.setCurrent(file_info.absoluteDir().path()) root = QgsLayerTreeGroup() ids = doc.elementsByTagName('id') for i in xrange(0, ids.size()): id_node = ids.at(i) id_elem = id_node.toElement() old_id = id_elem.text() layer_name = old_id[:-17] date_time = QDateTime.currentDateTime() new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz') id_elem.firstChild().setNodeValue(new_id) tree_layer_nodes = doc.elementsByTagName('layer-tree-layer') for j in xrange(0, tree_layer_nodes.count()): layer_node = tree_layer_nodes.at(j) layer_elem = layer_node.toElement() if old_id == layer_elem.attribute('id'): layer_node.toElement().setAttribute('id', new_id) layer_tree_elem = doc.documentElement().firstChildElement('layer-tree-group') load_in_legend = True if not layer_tree_elem.isNull(): root.readChildrenFromXML(layer_tree_elem) load_in_legend = False layers = QgsMapLayer.fromLayerDefinition(doc) QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend) nodes = root.children() for node in nodes: root.takeChild(node) del root root_group.insertChildNodes(-1, nodes) return None
def load(self, fname): """Loads information of a *.tool file to actual Tool object. fname is tool name plus the extension (name.tool)""" self.name = fname.split(".")[0] fh = QFile("tools/" + fname) fh.open(QIODevice.ReadOnly) dom = QDomDocument() dom.setContent(fh) fh.close() root = dom.documentElement() if root.tagName() != "TOOL": raise ValueError, "not a Tool XML file" self.tipDiam = str(root.attribute("TIPDIAM")) self.syrDiam = str(root.attribute("SYRDIAM")) self.pathWidth = str(root.attribute("PATHWIDTH")) self.pathHeight = str(root.attribute("PATHHEIGHT")) self.jogSpeed = str(root.attribute("JOGSPEED")) self.suckback = str(root.attribute("SUCKBACK")) self.pushout = str(root.attribute("PUSHOUT")) self.pathSpeed = str(root.attribute("PATHSPEED")) self.pausePaths = str(root.attribute("PAUSEPATHS")) self.clearance = str(root.attribute("CLEARANCE")) self.depRate = str(root.attribute("DEPOSITIONRATE"))
class Opener: ''' Opens and return the root node of a XML document ''' def __init__(self, filepath, mode=QIODevice.ReadWrite): ''' @summary Constructor @param filePath : XML file's path @param mode : QIODevice.OpenMode ''' self.temp_dom = QDomDocument() self.fpath = filepath self.omode = mode self.openf() def openf(self): ''' @summary Open file. On success, store root node in self.temp_dom ''' assert QFile(self.fpath).exists(), "In Opener::openf : Cannot open File : " + self.fpath + ", file does not exist!" f = QFile(self.fpath) if f.open(self.omode): assert self.temp_dom.setContent(f), "In Opener::openf() : unable to parse XML dom of " + self.fpath else: print("Warning in Opener::openf() : unable to open", self.fpath) f.close() def getRootNode(self): ''' @summary Return root node ''' return self.temp_dom.documentElement() def getDomDocument(self): ''' @summary Return QDomDocument instance ''' return self.temp_dom
def __getActivePlugins(self, xmlfile=None): ''' Function checks xml and returns if plugin was active on previous program execution xmlfile: specifies alternative path to xml file with plugin information (default: plugins/plugins.xml) ''' fname = self.xmlFile if xmlfile != None: fname = xmlfile if os.path.exists(fname): fileObject = QFile(fname) Xml = QDomDocument("xmldoc") Xml.clear() if (fileObject.open(QIODevice.ReadOnly) != False): Xml.setContent(fileObject.readAll()) fileObject.close() rootNode = Xml.documentElement() nodeList = rootNode.elementsByTagName("plugin") for i in range(nodeList.length()): bpNode = nodeList.at(i).toElement() for a in self.pluginActions: if a.path == str(bpNode.attribute("path")): a.setChecked(bpNode.attribute("active") == "y")
def importFromXml(self, fn): f = QFile(fn) if not f.exists() or not f.open(QIODevice.ReadOnly): QMessageBox.warning(None, "Importing", "File not found.") return False if f.size() <= 0 or f.atEnd(): return False from PyQt4.QtXml import QDomDocument doc = QDomDocument(self.XML_TRANSF_DOC) (ok, errMsg, errLine, errCol) = doc.setContent(f, False) f.close() if not ok: QMessageBox.warning( None, "Importing", "Failed to parse file: line %s col %s" % (errLine, errCol)) return False root = doc.documentElement() if root.tagName() == self.XML_TRANSF_LIST_TAG: node = root.firstChild() while not node.isNull(): if node.toElement().tagName() == self.XML_TRANSF_TAG: t = Transformation() if t._fromNode(node): if t.inGrid != None: finfo = QFileInfo(t.inGrid) if not finfo.exists(): t.inGrid = finfo.fileName() t.saveData() node = node.nextSibling() return True
def init_config(self): if not os.path.exists(os.getenv("HOME") + "/.qtsixa2/"): os.mkdir(os.getenv("HOME") + "/.qtsixa2/") if not os.path.exists(os.getenv("HOME") + "/.qtsixa2/profiles"): os.mkdir(os.getenv("HOME") + "/.qtsixa2/profiles") if not os.path.exists(os.getenv("HOME") + "/.qtsixa2/conf.xml"): filename = QFile(os.getenv("HOME") + "/.qtsixa2/conf.xml") if not filename.open(QIODevice.WriteOnly): QMessageBox.critical( self, self.tr("QtSixA - Error"), self.tr("Cannot write QtSixA configuration file!")) raise IOError, unicode(filename.errorString()) stream = QTextStream(filename) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE QTSIXA>\n" "<QTSIXA VERSION='1.5.1'>\n" " <Configuration>\n" " <Main>\n" " <Show-Warnings>true</Show-Warnings>\n" " <Only-One-Instance>true</Only-One-Instance>\n" " </Main>\n" " <Systray>\n" " <Enable>true</Enable>\n" " <Start-Minimized>false</Start-Minimized>\n" " <Close-to-Tray>false</Close-to-Tray>\n" " </Systray>\n" " </Configuration>\n" "</QTSIXA>\n") Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False else: # Set Default Values, only change them if the config says so Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False # Read configuration file xml = QDomDocument() filename = QFile(os.getenv("HOME") + "/.qtsixa2/conf.xml") if not filename.open(QIODevice.ReadOnly): print "error here, 1" if not xml.setContent(filename): print "error here, 2" filename.close() # Check if project file is not corrupted content = xml.documentElement() if (content.tagName() != "QTSIXA"): print "error here, 3" # Get values from XML - the big code node = content.firstChild() while not node.isNull(): if (node.toElement().tagName() == "Configuration"): configuration = node.toElement().firstChild() while not configuration.isNull(): conf_tag = configuration.toElement().tagName() if (conf_tag == "Main"): conf_tag_main = configuration.toElement().firstChild() while not conf_tag_main.isNull(): name = conf_tag_main.toElement().tagName() text = conf_tag_main.toElement().text() if (name == "Show-Warnings"): if (text == "0" or text == "false" or text == "False"): Globals.show_warnings = False elif (name == "Only-One-Instance"): if (text == "0" or text == "false" or text == "False"): Globals.only_one_instance = False conf_tag_main = conf_tag_main.nextSibling() elif (conf_tag == "Systray"): conf_tag_systray = configuration.toElement( ).firstChild() while not conf_tag_systray.isNull(): name = conf_tag_systray.toElement().tagName() text = conf_tag_systray.toElement().text() if (name == "Enable"): if (text == "0" or text == "false" or text == "False"): Globals.systray_enabled = False elif (name == "Start-Minimized"): if (text == "1" or text == "true" or text == "True"): Globals.start_minimized = True elif (name == "Close-to-Tray"): if (text == "1" or text == "true" or text == "True"): Globals.close_to_tray = True conf_tag_systray = conf_tag_systray.nextSibling() configuration = configuration.nextSibling() node = node.nextSibling()
def load(self, fname): self.name = fname.split('.')[0] fh = QFile('config/' + fname) fh.open(QIODevice.ReadOnly) dom = QDomDocument() dom.setContent(fh) fh.close() root = dom.documentElement() if root.tagName() != "PRINTER": raise ValueError, "not a Printer XML file" self.updatePeriod = str(root.attribute("UPDATEPERIOD")) self.jogSpeed = str(root.attribute("JOGSPEED")) self.maxTools = str(root.attribute("MAXTOOLS")) self.toolLimit = str(root.attribute("TOOLLIMIT")) self.maxAccel = str(root.attribute("MAXACCEL")) self.xMax = str(root.attribute("XMAX")) self.yMax = str(root.attribute("YMAX")) self.zMax = str(root.attribute("ZMAX")) ## Base root = root.firstChild() child = root.toElement() self.base.direction = str(child.attribute("DIRECTION")) self.base.motor = str(child.attribute("MOTOR")) self.base.arange = str(child.attribute("RANGE")) self.base.limits = str(child.attribute("LIMITS")) self.base.increment = str(child.attribute("INCREMENT")) ## X Axis root = root.nextSibling() child = root.toElement() self.x.direction = str(child.attribute("DIRECTION")) self.x.motor = str(child.attribute("MOTOR")) self.x.arange = str(child.attribute("RANGE")) self.x.limits = str(child.attribute("LIMITS")) self.x.increment = str(child.attribute("INCREMENT")) ## Y Axis root = root.nextSibling() child = root.toElement() self.y.direction = str(child.attribute("DIRECTION")) self.y.motor = str(child.attribute("MOTOR")) self.y.arange = str(child.attribute("RANGE")) self.y.limits = str(child.attribute("LIMITS")) self.y.increment = str(child.attribute("INCREMENT")) ## Z Axis root = root.nextSibling() child = root.toElement() self.z.direction = str(child.attribute("DIRECTION")) self.z.motor = str(child.attribute("MOTOR")) self.z.arange = str(child.attribute("RANGE")) self.z.limits = str(child.attribute("LIMITS")) self.z.increment = str(child.attribute("INCREMENT")) ## U Axis root = root.nextSibling() child = root.toElement() self.u.direction = str(child.attribute("DIRECTION")) self.u.motor = str(child.attribute("MOTOR")) self.u.arange = str(child.attribute("RANGE")) self.u.limits = str(child.attribute("LIMITS")) self.u.increment = str(child.attribute("INCREMENT")) ## V Axis if int(self.maxTools) == 2: root = root.nextSibling() child = root.toElement() self.v.direction = str(child.attribute("DIRECTION")) self.v.motor = str(child.attribute("MOTOR")) self.v.arange = str(child.attribute("RANGE")) self.v.limits = str(child.attribute("LIMITS")) self.v.increment = str(child.attribute("INCREMENT"))
class XmlHandler(): ''' Handler used to save session info to an xml file. ''' def __init__(self, distributedObjects, rootname): self.Xml = QDomDocument("xmldoc") self.rootname = rootname self.rootNode = QDomElement() self.clear() def createNode(self, nodeName, parentNode=None, withAttribs={}): ''' Create and insert node @param nodeName: String representing name of node @param parentNode: QDomElement representing parent node. Root will be parent if this is None @param withAttribs: dict with node attributes @return node on success, None on error ''' if isinstance(nodeName, str) and len(nodeName) != 0: node = self.Xml.createElement(nodeName) if isinstance(withAttribs, dict) and withAttribs != {}: for key, value in withAttribs.items(): node.setAttribute(key, value) if parentNode == None: self.rootNode.appendChild(node) else: if isinstance(parentNode, QDomElement): parentNode.appendChild(node) return node return None def getNode(self, nodeName, parent=None): ''' Get first xml node by name @return QDomElement ''' if isinstance(nodeName, str) and len(nodeName) != 0: if parent == None or not isinstance(parent, QDomNode): return self.rootNode.firstChildElement(nodeName) else: return parent.firstChildElement(nodeName) def getAttributes(self, node): ''' Get a dict with attributes of node @param node: QDomElement @return dict(QString, QString) with attributes ''' attribs = {} if isinstance(node, QDomElement) or isinstance(node, QDomNode): namedNodeMap = node.attributes() for i in range(namedNodeMap.count()): item = namedNodeMap.item(i) attribs[str(item.nodeName())] = str(item.nodeValue()) return attribs def save(self, filename): """Writes session info to xml file. Overwrites existing files""" if not filename.endswith(".xml"): filename = filename + ".xml" file_object = QFile(filename) if not file_object.open(QIODevice.WriteOnly): logging.error("File %s could not be opened.", filename) else: file_object.writeData(self.Xml.toString()) file_object.close() def clear(self): ''' Clear xml doc and reset root node''' self.Xml.clear() self.rootNode = self.Xml.createElement(self.rootname) self.Xml.appendChild(self.rootNode) def load(self, filename): """Loads session info from xml file. Returns false if loading fails, true otherwise.""" if not exists(filename): logging.error("Cannot restore session - File %s not found.", filename) return False file_object = QFile(filename) self.Xml.clear() if not file_object.open(QIODevice.ReadOnly): logging.error("File %s could not be opened.", filename) return False else: if not self.Xml.setContent(file_object.readAll()): logging.error("self.Xml.setContent() failed.") file_object.close() return False file_object.close() self.rootNode = self.Xml.documentElement() return True
class XmlHandler(): ''' Handler used to save session info to an xml file. ''' def __init__(self, distributedObjects, rootname): self.Xml = QDomDocument("xmldoc") self.rootname = rootname self.rootNode = QDomElement() self.clear() def createNode(self, nodeName, parentNode=None, withAttribs={}): ''' Create and insert node @param nodeName: String representing name of node @param parentNode: QDomElement representing parent node. Root will be parent if this is None @param withAttribs: dict with node attributes @return node on success, None on error ''' if isinstance(nodeName, str) and len(nodeName) != 0: node = self.Xml.createElement(nodeName) if isinstance(withAttribs, dict) and withAttribs != {}: for key, value in withAttribs.items(): node.setAttribute(key, value) if parentNode == None: self.rootNode.appendChild(node) else: if isinstance(parentNode, QDomElement): parentNode.appendChild(node) return node return None def getNode(self, nodeName, parent=None): ''' Get first xml node by name @return QDomElement ''' if isinstance(nodeName, str) and len(nodeName) != 0: if parent == None or not isinstance(parent, QDomNode): return self.rootNode.firstChildElement(nodeName) else: return parent.firstChildElement(nodeName) def getAttributes(self, node): ''' Get a dict with attributes of node @param node: QDomElement @return dict(QString, QString) with attributes ''' attribs = {} if isinstance(node, QDomElement) or isinstance(node, QDomNode): namedNodeMap = node.attributes() for i in xrange(namedNodeMap.count()): item = namedNodeMap.item(i) attribs[str(item.nodeName())] = str(item.nodeValue()) return attribs def save(self, filename): """Writes session info to xml file. Overwrites existing files""" if not filename.endswith(".xml"): filename = filename + ".xml" file_object = QFile(filename) if not file_object.open(QIODevice.WriteOnly): logging.error("File %s could not be opened.", filename) else: file_object.writeData(self.Xml.toString()) file_object.close() def clear(self): ''' Clear xml doc and reset root node''' self.Xml.clear() self.rootNode = self.Xml.createElement(self.rootname) self.Xml.appendChild(self.rootNode) def load(self, filename): """Loads session info from xml file. Returns false if loading fails, true otherwise.""" if not exists(filename): logging.error("Cannot restore session - File %s not found.", filename) return False file_object = QFile(filename) self.Xml.clear() if not file_object.open(QIODevice.ReadOnly): logging.error("File %s could not be opened.", filename) return False else: if not self.Xml.setContent(file_object.readAll()): logging.error("self.Xml.setContent() failed.") file_object.close() return False file_object.close() self.rootNode = self.Xml.documentElement() return True
def loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related composer items. """ if not QFile.exists(filePath): QMessageBox.critical(self.composerView(), QApplication.translate("OpenTemplateConfig", "Open Template Error"), QApplication.translate("OpenTemplateConfig", "The specified template does not exist.")) return templateFile = QFile(filePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper", "Open Operation Error"), "{0}\n{1}".format(QApplication.translate( "ComposerWrapper", "Cannot read template file."), templateFile.errorString() )) return templateDoc = QDomDocument() if templateDoc.setContent(templateFile): table_config_collection = TableConfigurationCollection.create(templateDoc) ''' First load vector layers for the table definitions in the config collection before loading rhe composition from file. ''' load_table_layers(table_config_collection) #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) self.clearWidgetMappings() #Load data controls composerDS = ComposerDataSource.create(templateDoc) #Set title by appending template name title = QApplication.translate("STDMPlugin", "STDM Document Designer") composer_el = templateDoc.documentElement() if not composer_el is None: template_name = "" if composer_el.hasAttribute("title"): template_name = composer_el.attribute("title", "") elif composer_el.hasAttribute("_title"): template_name = composer_el.attribute("_title", "") if template_name: win_title = u"{0} - {1}".format(title, template_name) self.mainWindow().setWindowTitle(template_name) self._configure_data_controls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create(templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig) #Load photo editors photo_config_collection = PhotoConfigurationCollection.create(templateDoc) self._configure_photo_editors(photo_config_collection) #Load table editors self._configure_table_editors(table_config_collection) #Load chart property editors chart_config_collection = ChartConfigurationCollection.create(templateDoc) self._configure_chart_editors(chart_config_collection) self._sync_ids_with_uuids()
class ConfigurationUtils: PROFILE = 'Profile' SOCIAL_TENURE = 'SocialTenure' CONFIGURATION = 'Configuration' def __init__(self, document): """ A utility class for STDM configuration. :param document: The configuration :type document: QDomDocument """ self.file_handler = FilePaths() self.log_file_path = '{}/logs/migration.log'.format( self.file_handler.localPath()) self.document = document def append_log(self, info): """ Append info to a single file :param info: update information to save to file :type info: str """ info_file = open(self.log_file_path, "a") time_stamp = datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S') info_file.write('\n') info_file.write('{} - '.format(time_stamp)) info_file.write(info) info_file.write('\n') info_file.close() def check_config_file_exists(self, config_file): """ Checks if config file exists :returns True if folder exists else False :rtype bool """ if os.path.isfile( os.path.join(self.file_handler.localPath(), config_file)): return True else: return False def read_stc(self, config_file_name): """ Reads provided config file :returns QDomDocument, QDomDocument.documentElement() :rtype tuple """ config_file_path = os.path.join(self.file_handler.localPath(), config_file_name) config_file_path = QFile(config_file_path) config_file = os.path.basename(config_file_name) if self.check_config_file_exists(config_file): self.document = QDomDocument() status, msg, line, col = self.document.setContent(config_file_path) if not status: error_message = u'Configuration file cannot be loaded: {0}'. \ format(msg) self.append_log(str(error_message)) raise ConfigurationException(error_message) self.doc_element = self.document.documentElement() def find_node(self, name): """ Get nodes inside a document by a tag name. :param document: The xml document :type document: QDomDocument :param name: the tag name :type name: String :return: The nodes list :rtype: List """ node_list = self.document.elementsByTagName(name) nodes = [] for i in range(node_list.length()): node = node_list.item(i) nodes.append(node) return nodes def add_attribute_to_nodes(self, nodes, attr, value): """ Adds an attribute with value to node lists. :param nodes: List of nodes :type nodes: QNodeList :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ for node in nodes: element = node.toElement() element.setAttribute(attr, value) def add_attribute_by_node_name(self, node_name, attr, value): """ Add attribute with value to nodes by node name. :param node_name: The name of the node. :type node_name: Strong :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ nodes = self.find_node(node_name) self.add_attribute_to_nodes(nodes, attr, value) def profile_first_child(self, tag_name): """ Gets the first child of profile node with a specified tag name. :param tag_name: The tag name to be used to search the child. :type tag_name: String :return: Dictionary of parent (profile node) and the child element. :rtype: OrderedDict """ profile_nodes = self.find_node(self.PROFILE) first_child = OrderedDict() for profile_node in profile_nodes: profile_child = profile_node.firstChildElement(tag_name) first_child[profile_node] = profile_child return first_child def social_tenure_elements(self): """ Get all social tenure element in a dom_document. :return: List of social tenure element :rtype: OrderedDict """ social_tenure_nodes = self.profile_first_child(self.SOCIAL_TENURE) return social_tenure_nodes def run(self): nodes = self.find_node('Entity') self.add_attribute_to_nodes(nodes, 'Test', 'One')
def check_pat_symbols(): pat_xml = os.path.join(PLUGIN_DIR, 'PAT_Symbols.xml') if not os.path.exists(pat_xml): return loaded_date = read_setting(PLUGIN_NAME + "/PAT_SYMBOLOGY") if loaded_date is not None: loaded_date = datetime.strptime(loaded_date,'%Y-%m-%d %H:%M:%S') xml_date = datetime.fromtimestamp(os.path.getmtime(pat_xml)).replace(microsecond=0) if loaded_date is None or xml_date > loaded_date: style = QgsStyleV2.defaultStyle() # add a group if it doesn't exist. group_id = style.groupId('PAT') if group_id == 0: group_id = style.addGroup('PAT') xml_file = QFile(pat_xml) document = QDomDocument() if not document.setContent(xml_file): LOGGER.debug('Could not open file {}'.format(xml_file)) return xml_file.close() document_element = document.documentElement() if document_element.tagName() != 'qgis_style': LOGGER.debug("File {} doesn't contain qgis styles".format(xml_file)) return # Get all the symbols symbols = [] symbols_element = document_element.firstChildElement('symbols') symbol_element = symbols_element.firstChildElement() while not symbol_element.isNull(): if symbol_element.tagName() == 'symbol': symbol = QgsSymbolLayerV2Utils.loadSymbol(symbol_element) if symbol: symbols.append({ 'name': symbol_element.attribute('name'), 'symbol': symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps colorramps = [] ramps_element = document_element.firstChildElement('colorramps') ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == 'colorramp': colorramp = QgsSymbolLayerV2Utils.loadColorRamp(ramp_element) if colorramp: colorramps.append({ 'name': ramp_element.attribute('name'), 'colorramp': colorramp }) ramp_element = ramp_element.nextSiblingElement() for symbol in symbols: if style.addSymbol(symbol['name'], symbol['symbol'], True): style.group(QgsStyleV2.SymbolEntity, symbol['name'], group_id) for colorramp in colorramps: if style.addColorRamp(colorramp['name'], colorramp['colorramp'], True): style.group(QgsStyleV2.ColorrampEntity, colorramp['name'], group_id) LOGGER.info( 'Loaded {} symbols and {} colour ramps into group {}'.format(len(symbols), len(colorramps), style.groupName(group_id))) write_setting(PLUGIN_NAME + '/PAT_SYMBOLOGY', xml_date.strftime('%Y-%m-%d %H:%M:%S')) return
def init_config(self): if not os.path.exists(os.getenv("HOME")+"/.qtsixa2/"): os.mkdir(os.getenv("HOME")+"/.qtsixa2/") if not os.path.exists(os.getenv("HOME")+"/.qtsixa2/profiles"): os.mkdir(os.getenv("HOME")+"/.qtsixa2/profiles") if not os.path.exists(os.getenv("HOME")+"/.qtsixa2/conf.xml"): filename = QFile(os.getenv("HOME")+"/.qtsixa2/conf.xml") if not filename.open(QIODevice.WriteOnly): QMessageBox.critical(self, self.tr("QtSixA - Error"), self.tr("Cannot write QtSixA configuration file!")) raise IOError, unicode(filename.errorString()) stream = QTextStream(filename) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE QTSIXA>\n" "<QTSIXA VERSION='1.5.1'>\n" " <Configuration>\n" " <Main>\n" " <Show-Warnings>true</Show-Warnings>\n" " <Only-One-Instance>true</Only-One-Instance>\n" " </Main>\n" " <Systray>\n" " <Enable>true</Enable>\n" " <Start-Minimized>false</Start-Minimized>\n" " <Close-to-Tray>false</Close-to-Tray>\n" " </Systray>\n" " </Configuration>\n" "</QTSIXA>\n" ) Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False else: # Set Default Values, only change them if the config says so Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False # Read configuration file xml = QDomDocument() filename = QFile(os.getenv("HOME")+"/.qtsixa2/conf.xml") if not filename.open(QIODevice.ReadOnly): print "error here, 1" if not xml.setContent(filename): print "error here, 2" filename.close() # Check if project file is not corrupted content = xml.documentElement() if (content.tagName() != "QTSIXA"): print "error here, 3" # Get values from XML - the big code node = content.firstChild() while not node.isNull(): if (node.toElement().tagName() == "Configuration"): configuration = node.toElement().firstChild() while not configuration.isNull(): conf_tag = configuration.toElement().tagName() if (conf_tag == "Main"): conf_tag_main = configuration.toElement().firstChild() while not conf_tag_main.isNull(): name = conf_tag_main.toElement().tagName() text = conf_tag_main.toElement().text() if (name == "Show-Warnings"): if (text == "0" or text == "false" or text == "False"): Globals.show_warnings = False elif (name == "Only-One-Instance"): if (text == "0" or text == "false" or text == "False"): Globals.only_one_instance = False conf_tag_main = conf_tag_main.nextSibling() elif (conf_tag == "Systray"): conf_tag_systray = configuration.toElement().firstChild() while not conf_tag_systray.isNull(): name = conf_tag_systray.toElement().tagName() text = conf_tag_systray.toElement().text() if (name == "Enable"): if (text == "0" or text == "false" or text == "False"): Globals.systray_enabled = False elif (name == "Start-Minimized"): if (text == "1" or text == "true" or text == "True"): Globals.start_minimized = True elif (name == "Close-to-Tray"): if (text == "1" or text == "true" or text == "True"): Globals.close_to_tray = True conf_tag_systray = conf_tag_systray.nextSibling() configuration = configuration.nextSibling() node = node.nextSibling()
class ConfigurationUtils(): PROFILE = 'Profile' SOCIAL_TENURE = 'SocialTenure' CONFIGURATION = 'Configuration' def __init__(self, document): """ A utility class for STDM configuration. :param document: The configuration :type document: QDomDocument """ self.file_handler = FilePaths() self.log_file_path = '{}/logs/migration.log'.format( self.file_handler.localPath() ) self.document = document def append_log(self, info): """ Append info to a single file :param info: update information to save to file :type info: str """ info_file = open(self.log_file_path, "a") time_stamp = datetime.datetime.now().strftime( '%d-%m-%Y %H:%M:%S' ) info_file.write('\n') info_file.write('{} - '.format(time_stamp)) info_file.write(info) info_file.write('\n') info_file.close() def check_config_file_exists(self, config_file): """ Checks if config file exists :returns True if folder exists else False :rtype bool """ if os.path.isfile(os.path.join( self.file_handler.localPath(), config_file) ): return True else: return False def read_stc(self, config_file_name): """ Reads provided config file :returns QDomDocument, QDomDocument.documentElement() :rtype tuple """ config_file_path = os.path.join( self.file_handler.localPath(), config_file_name ) config_file_path = QFile(config_file_path) config_file = os.path.basename(config_file_name) if self.check_config_file_exists(config_file): self.document = QDomDocument() status, msg, line, col = self.document.setContent(config_file_path) if not status: error_message = u'Configuration file cannot be loaded: {0}'.\ format(msg) self.append_log(str(error_message)) raise ConfigurationException(error_message) self.doc_element = self.document.documentElement() def find_node(self, name): """ Get nodes inside a document by a tag name. :param document: The xml document :type document: QDomDocument :param name: the tag name :type name: String :return: The nodes list :rtype: List """ node_list = self.document.elementsByTagName(name) nodes = [] for i in range(node_list.length()): node = node_list.item(i) nodes.append(node) return nodes def add_attribute_to_nodes(self, nodes, attr, value): """ Adds an attribute with value to node lists. :param nodes: List of nodes :type nodes: QNodeList :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ for node in nodes: element = node.toElement() element.setAttribute(attr, value) def add_attribute_by_node_name(self, node_name, attr, value): """ Add attribute with value to nodes by node name. :param node_name: The name of the node. :type node_name: Strong :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ nodes = self.find_node(node_name) self.add_attribute_to_nodes(nodes, attr, value) def profile_first_child(self, tag_name): """ Gets the first child of profile node with a specified tag name. :param tag_name: The tag name to be used to search the child. :type tag_name: String :return: Dictionary of parent (profile node) and the child element. :rtype: OrderedDict """ profile_nodes = self.find_node(self.PROFILE) first_child = OrderedDict() for profile_node in profile_nodes: profile_child = profile_node.firstChildElement( tag_name ) first_child[profile_node] = profile_child return first_child def social_tenure_elements(self): """ Get all social tenure element in a dom_document. :return: List of social tenure element :rtype: OrderedDict """ social_tenure_nodes = self.profile_first_child( self.SOCIAL_TENURE ) return social_tenure_nodes def run(self): nodes = self.find_node('Entity') self.add_attribute_to_nodes(nodes, 'Test', 'One')
def doXml(self, operate): self.listWidget.clear() self.listWidget.addItem(QString("没有找到相关内容!")) file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open file Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if (not status): file.close() raise Exception(str(rrorMsg)) file.close() # 以标签名进行查找 list = doc.elementsByTagName(QString("图书")) # 获取所有图书元素的列表 for i in range(list.count()): e = list.at(i).toElement() if (e.attribute(QString("编号")) == self.lineEdit.text()): # 如果元素的“编号”属性值与我们所查的相同 if (operate == "delete"): # 如果是删除操作 root = doc.documentElement() # 从根节点上删除该节点 root.removeChild(list.at(i)) file = QFile("my.xml") if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("open file Err") out = QTextStream(file) doc.save(out, 4) file.close() self.listWidget.clear() self.listWidget.addItem(QString("删除成功!")) elif operate is "update": # 如果是更新操作 child = list.at(i).childNodes() # 将它子节点的首个子节点(就是文本节点)的内容更新 child.at(0).toElement().firstChild().setNodeValue( self.lineEdit_2.text()) child.at(1).toElement().firstChild().setNodeValue( self.lineEdit_3.text()) file = QFile("my.xml") if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("Open file Err") out = QTextStream(file) doc.save(out, 4) file.close() self.listWidget.clear() self.listWidget.addItem(QString("更新成功!")) elif operate is "find": # 如果是查找操作 self.listWidget.clear() self.listWidget.addItem(e.tagName() + e.attribute(QString("编号"))) list = e.childNodes() for i in range(list.count()): node = list.at(i) if (node.isElement()): self.listWidget.addItem( " " + node.toElement().tagName() + " : " + node.toElement().text())
class CImportR78_p48_FLG(): def __init__(self, args): connectionInfo = { 'driverName': 'MYSQL', 'host': args['host'], 'port': args['port'], 'database': args['database'], 'user': args['user'], 'password': args['password'], 'connectionName': 'IEMK', 'compressData': True, 'afterConnectFunc': None } self.db = database.connectDataBaseByInfo(connectionInfo) QtGui.qApp.db = self.db self.tableClient = self.db.table('Client') self.tableClientAddress = self.db.table('ClientAddress') self.tableEvent = self.db.table('Event') self.tableAction = self.db.table('Action') self.nProcessed = 0 self.nUpdated = 0 self.nAdded = 0 # Допустимые коды - FLG, FLG47. accSystemCode = args['accSystem'] self.accountingSystem = forceRef( self.db.translate('rbAccountingSystem', 'code', accSystemCode, 'id')) self.actionType = forceRef( self.db.translate('ActionType', 'code', u'А06.09.007.002*', 'id')) self._mapIDOtoIDI = { } # соответствие внешних и локальных идентификаторов пациентов def readFile(self, device): """ Обработка импортируемого файла """ self.doc = QDomDocument() self.doc.setContent(device, False) root = self.doc.documentElement() if root.tagName() != u'doc': print 'Error: incorrect root element. Import aborted.' return -1 clients = root.firstChildElement('demography') results = root.firstChildElement('results') if not (clients and results): print 'Incorrect xml structure. Import aborted' return -2 self.processRegData(clients.childNodes()) self.processResults(results.childNodes()) return 0 def processRegData(self, clients): for i in range(clients.length()): client = clients.at(i) localId = client.firstChildElement('ido').text() if not localId: externalId = client.firstChildElement('idi').text() record = self.db.getRecordEx( 'ClientIdentification', 'client_id', 'identifier = \'%s\' AND accountingSystem_id = %s' % (externalId, self.accountingSystem)) if record: self._mapIDOtoIDI[externalId] = forceRef(record.value(0)) continue lastName = client.firstChildElement('lastname').text() firstName = client.firstChildElement('firstname').text() patrName = client.firstChildElement('midlname').text() sex = forceInt(client.firstChildElement('sex').text()) birthDate = QDate.fromString( client.firstChildElement('dob').text(), Qt.ISODate) cond = [ self.tableClient['lastName'].eq(lastName), self.tableClient['firstName'].eq(firstName), self.tableClient['patrName'].eq(patrName), self.tableClient['sex'].eq(1 if sex == 0 else 2 if sex == 1 else 0), self.tableClient['birthDate'].eq(birthDate) ] record = self.db.getRecordEx(self.tableClient, 'id', cond) if record: self._mapIDOtoIDI[externalId] = forceRef(record.value(0)) continue record = self.tableClient.newRecord() record.setValue('lastName', toVariant(lastName)) record.setValue('firstName', toVariant(firstName)) record.setValue('patrName', toVariant(patrName)) record.setValue( 'sex', toVariant(1 if sex == 0 else 2 if sex == 1 else 0)) record.setValue('birthDate', toVariant(birthDate)) address = client.firstChildElement('address') if address: city = address.firstChildElement('sity').text() street = address.firstChildElement('street').text() streetSocr = address.firstChildElement('streetSokr').text() number = address.firstChildElement('house').text() corpus = address.firstChildElement('corpus').text() flat = address.firstChildElement('flat').text() freeInput = u'' if city: freeInput = city if street: if freeInput: freeInput += u', ' freeInput += street if streetSocr: freeInput += ' ' + streetSocr if number: if freeInput: freeInput += u', ' freeInput += u'Д. ' + number if corpus: if freeInput: freeInput += u', ' freeInput += u'К. ' + corpus if flat: if freeInput: freeInput += u', ' freeInput += u'КВ. ' + flat addrRecord = self.tableClientAddress.newRecord() addrRecord.setValue('freeInput', toVariant(freeInput)) addrRecord.setValue('type', toVariant(0)) self.db.transaction() try: clientId = self.db.insertRecord( self.tableClient, record) addrRecord.setValue('client_id', toVariant(clientId)) self.db.insertRecord(self.tableClientAddress, addrRecord) self.db.commit() except: self.db.rollback() raise else: clientId = self.db.insertRecord(self.tableClient, record) self._mapIDOtoIDI[externalId] = forceRef(clientId) def processResults(self, results): defaultEventTypeId = forceRef( self.db.translate('EventType', 'code', '001', 'id')) tableJobTicket = self.db.table('Job_Ticket').alias('jt') tableAction = self.db.table('Action').alias('a') currentDate = QDate.currentDate() for i in range(results.length()): result = results.at(i) localId = result.firstChildElement('ido').text() externalId = result.firstChildElement('idi').text() tests = result.firstChildElement('tests') if not tests: continue test = tests.firstChildElement('test') if not test: continue dateString = test.firstChildElement('date').text() date = QDate.fromString(dateString, Qt.ISODate) value = test.firstChildElement('value').text() status = test.firstChildElement('status').text() comment = test.firstChildElement('comment').text() if localId: stmt = u'''SELECT a.id as actionId, Event.id as eventId FROM Job_Ticket jt INNER JOIN Job j ON j.id = jt.master_id AND jt.status = 0 INNER JOIN rbJobType jt1 ON jt1.code = '4-4' AND jt1.id= j.jobType_id INNER JOIN ActionProperty_Job_Ticket apjt ON apjt.value = jt.id INNER JOIN ActionProperty ap ON ap.id = apjt.id INNER JOIN Action a ON a.id = ap.action_id AND a.deleted = 0 INNER JOIN Event ON Event.id = a.event_id AND Event.deleted = 0 INNER JOIN Client c ON c.id = Event.client_id AND c.deleted = 0 WHERE %s''' cond = [ self.tableEvent['client_id'].eq(forceRef(localId)), tableJobTicket['datetime'].dateEq(date), tableAction['actionType_id'].eq(self.actionType) ] query = self.db.query(stmt % self.db.joinAnd(cond)) if not query.first(): continue record = query.record() eventId = forceRef(record.value('eventId')) action = CAction.getAction(eventId, u'А06.09.007.002*') actionRecord = action.getRecord() endDate = forceDate(actionRecord.value('endDate')) if not endDate: actionRecord.setValue('endDate', toVariant(currentDate)) actionRecord.setValue( 'status', toVariant(2 if status == 1 else 3 if status == 2 else 0)) action[u'Результат'] = externalId + u' ' + value action[u'Описание'] = comment action.setRecord(actionRecord) action.save() elif defaultEventTypeId: localId = self._mapIDOtoIDI.get(externalId, None) if localId is None: print 'Error: found test result without information about client. Skipping.' continue self.db.transaction() try: eventRecord = self.tableEvent.newRecord() eventRecord.setValue('eventType_id', toVariant(defaultEventTypeId)) eventRecord.setValue('client_id', toVariant(localId)) eventRecord.setValue('setDate', toVariant(date)) eventRecord.setValue('isPrimary', toVariant(1)) eventRecord.setValue('order', toVariant(1)) eventId = self.db.insertRecord('Event', eventRecord) action = CAction.createByTypeId(self.actionType) actionRecord = action.getRecord() if not actionRecord: actionRecord = self.tableAction.newRecord() actionRecord.setValue('actionType_id', toVariant(self.actionType)) actionRecord.setValue( 'status', toVariant(2 if status == 1 else 3 if status == 2 else 0)) actionRecord.setValue('begDate', toVariant(date)) actionRecord.setValue('endDate', toVariant(currentDate)) action[u'Результат'] = externalId + ' ' + value action[u'Описание'] = comment action.setRecord(actionRecord) action.save(eventId) self.db.commit() except: self.db.rollback() raise
raise Exception("err") # 将文件内容读到doc中 status, rrorMsg, errorLine, errorColumn = doc.setContent(_file) if not status: _file.close() raise Exception("err") _file.close() # firstChild 获得doc的第一个结点,即XML说明 firstNode = doc.firstChild() # 输出XML说明,nodeName()为“xml”,nodeValue()为版本和编码信息 print firstNode.nodeName(), ": ", firstNode.nodeValue() docelement = doc.documentElement() # 返回根元素 n = docelement.firstChild() # 返回根节点的第一个子结点 while (not n.isNull()): # 如果结点不为空,则转到下一个节点 if (n.isElement()): # 如果结点是元素 e = n.toElement() # 将其转换为元素 # 返回元素标记和id属性的值 print e.tagName(), ", ", e.attribute("id") list = e.childNodes() # 获得元素e的所有子结点的列表 for i in range(list.count()): # // 遍历该列表 node = list.at(i) if (node.isElement()): print " ", node.toElement().tagName(), " ", node.toElement( ).text()
def loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related composer items. """ if not QFile.exists(filePath): QMessageBox.critical( self.composerView(), QApplication.translate("OpenTemplateConfig", "Open Template Error"), QApplication.translate( "OpenTemplateConfig", "The specified template does not exist.")) return copy_file = filePath.replace('sdt', 'cpy') # remove existing copy file if QFile.exists(copy_file): copy_template = QFile(copy_file) copy_template.remove() orig_template_file = QFile(filePath) self.setDocumentFile(orig_template_file) # make a copy of the original orig_template_file.copy(copy_file) #templateFile = QFile(filePath) # work with copy templateFile = QFile(copy_file) self.copy_template_file = templateFile if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical( self.composerView(), QApplication.translate("ComposerWrapper", "Open Operation Error"), "{0}\n{1}".format( QApplication.translate("ComposerWrapper", "Cannot read template file."), templateFile.errorString())) return templateDoc = QDomDocument() if templateDoc.setContent(templateFile): table_config_collection = TableConfigurationCollection.create( templateDoc) ''' First load vector layers for the table definitions in the config collection before loading the composition from file. ''' load_table_layers(table_config_collection) self.clearWidgetMappings() #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) #Load data controls composerDS = ComposerDataSource.create(templateDoc) #Set title by appending template name title = QApplication.translate("STDMPlugin", "STDM Document Designer") composer_el = templateDoc.documentElement() if not composer_el is None: template_name = "" if composer_el.hasAttribute("title"): template_name = composer_el.attribute("title", "") elif composer_el.hasAttribute("_title"): template_name = composer_el.attribute("_title", "") if template_name: win_title = u"{0} - {1}".format(title, template_name) self.mainWindow().setWindowTitle(template_name) self._configure_data_controls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig) #Load photo editors photo_config_collection = PhotoConfigurationCollection.create( templateDoc) self._configure_photo_editors(photo_config_collection) # Load table editors self._configure_table_editors(table_config_collection) items = self.composerView().items() items = [] #Load chart property editors chart_config_collection = ChartConfigurationCollection.create( templateDoc) self._configure_chart_editors(chart_config_collection) # Load QR code property editors qrc_config_collection = QRCodeConfigurationCollection.create( templateDoc) self._configure_qr_code_editors(qrc_config_collection) self._sync_ids_with_uuids()