def parse_xml(response): stream = QXmlStreamReader(response) document = XmlNode() current_node = document path = [] while not stream.atEnd(): stream.readNext() if stream.isStartElement(): node = XmlNode() attrs = stream.attributes() for i in range(attrs.count()): attr = attrs.at(i) node.attribs[_node_name(attr.name())] = attr.value() current_node.append_child(_node_name(stream.name()), node) path.append(current_node) current_node = node elif stream.isEndElement(): current_node = path.pop() elif stream.isCharacters(): current_node.text += stream.text() return document
def __feedLoaded(self): """ Private slot to extract the loaded feed data. """ reply = self.sender() if id(reply) not in self.__replies: return topItem = self.__replies[id(reply)][1] del self.__replies[id(reply)] if reply.error() == QNetworkReply.NoError: linkString = "" titleString = "" xml = QXmlStreamReader() xmlData = reply.readAll() xml.addData(xmlData) while not xml.atEnd(): xml.readNext() if xml.isStartElement(): if xml.name() == "item": linkString = xml.attributes().value("rss:about") elif xml.name() == "link": linkString = xml.attributes().value("href") currentTag = xml.name() elif xml.isEndElement(): if xml.name() in ["item", "entry"]: itm = QTreeWidgetItem(topItem) itm.setText(0, titleString) itm.setData(0, FeedsManager.UrlStringRole, linkString) itm.setIcon(0, UI.PixmapCache.getIcon("rss16.png")) linkString = "" titleString = "" elif xml.isCharacters() and not xml.isWhitespace(): if currentTag == "title": titleString = xml.text() elif currentTag == "link": linkString += xml.text() if topItem.childCount() == 0: itm = QTreeWidgetItem(topItem) itm.setText(0, self.tr("Error fetching feed")) itm.setData(0, FeedsManager.UrlStringRole, "") itm.setData(0, FeedsManager.ErrorDataRole, str(xmlData, encoding="utf-8")) topItem.setExpanded(True) else: linkString = "" titleString = reply.errorString() itm = QTreeWidgetItem(topItem) itm.setText(0, titleString) itm.setData(0, FeedsManager.UrlStringRole, linkString) topItem.setExpanded(True)
def handleNetworkData(self, networkReply: QNetworkReply): if networkReply.error() == QNetworkReply.NoError: choices = [] response = networkReply.readAll() xml = QXmlStreamReader(response) while not xml.atEnd(): xml.readNext() if xml.tokenType() == QXmlStreamReader.StartElement: if xml.name() == 'suggestion': string = xml.attributes().value('data') choices.append(string) self.showCompletion(choices) networkReply.deleteLater()
def _parseResult(self, reply): xml = reply.readAll() reader = QXmlStreamReader(xml) while not reader.atEnd(): reader.readNext() if reader.name() != "geometry": continue reader.readNextStartElement() if reader.name() != "location": continue reader.readNextStartElement() if reader.name() != "lat": continue latitude = float(reader.readElementText()) reader.readNextStartElement() if reader.name() != "lng": continue longitude = float(reader.readElementText()) return latitude, longitude raise GeoCoder.NotFoundError
def read_xml_file(self, xml, tag): try: xml_file = QFile(os.path.join(os.curdir, 'in', xml)) xml_file.open(xml_file.ReadOnly | xml_file.Text) doc = QXmlStreamReader(xml_file) text_list = [] while not doc.atEnd(): doc.readNextStartElement() if doc.name() == tag: temp = doc.namespaceUri() text_list.append( '{0}, {1}, {2}'.format(doc.namespaceUri(), doc.qualifiedName(), doc.readElementText())) xml_file.close() return text_list finally: xml_file.close()
def handleResponse(self, reply): er = reply.error() if er == QtNetwork.QNetworkReply.NoError: data = reply.readAll() r = QXmlStreamReader(str(data, 'UTF-8')) while not r.atEnd(): r.readNext() if (r.qualifiedName() == "yweather:location"): if r.isStartElement(): atr = r.attributes() print("City:", atr.value("city")) print("Country:", atr.value("country")) if (r.qualifiedName() == "yweather:condition"): if r.isStartElement(): atr = r.attributes() print("Date:", atr.value("date")) print("Condition:", atr.value("text")) print("Temperature:", \ atr.value("temp"), "deg C") if r.hasError(): print("Error reading feed") else: print("Error occured: ", er) print(er) print(reply.errorString()) QCoreApplication.quit()
def __addDefaultActions(self): """ Private slot to add the default user agent entries. @return flag indicating that a user agent entry is checked (boolean) """ from . import UserAgentDefaults_rc # __IGNORE_WARNING__ defaultUserAgents = QFile(":/UserAgentDefaults.xml") defaultUserAgents.open(QIODevice.ReadOnly) menuStack = [] isChecked = False if self.__url: currentUserAgentString = self.__manager.userAgentForUrl(self.__url) else: from Helpviewer.HelpBrowserWV import HelpWebPage currentUserAgentString = HelpWebPage().userAgent() xml = QXmlStreamReader(defaultUserAgents) while not xml.atEnd(): xml.readNext() if xml.isStartElement() and xml.name() == "separator": if menuStack: menuStack[-1].addSeparator() else: self.addSeparator() continue if xml.isStartElement() and xml.name() == "useragent": attributes = xml.attributes() title = attributes.value("description") userAgent = attributes.value("useragent") act = QAction(self) act.setText(title) act.setData(userAgent) act.setToolTip(userAgent) act.setCheckable(True) act.setChecked(userAgent == currentUserAgentString) act.triggered.connect(self.__changeUserAgent) if menuStack: menuStack[-1].addAction(act) else: self.addAction(act) self.__actionGroup.addAction(act) isChecked = isChecked or act.isChecked() if xml.isStartElement() and xml.name() == "useragentmenu": attributes = xml.attributes() title = attributes.value("title") if title == "v_a_r_i_o_u_s": title = self.tr("Various") menu = QMenu(self) menu.setTitle(title) self.addMenu(menu) menuStack.append(menu) if xml.isEndElement() and xml.name() == "useragentmenu": menuStack.pop() if xml.hasError(): E5MessageBox.critical( self, self.tr("Parsing default user agents"), self.tr( """<p>Error parsing default user agents.</p><p>{0}</p>"""). format(xml.errorString())) return isChecked
def __addDefaultActions(self): """ Private slot to add the default user agent entries. @return flag indicating that a user agent entry is checked (boolean) """ from . import UserAgentDefaults_rc # __IGNORE_WARNING__ defaultUserAgents = QFile(":/UserAgentDefaults.xml") defaultUserAgents.open(QIODevice.ReadOnly) menuStack = [] isChecked = False if self.__url: currentUserAgentString = self.__manager.userAgentForUrl(self.__url) else: from Helpviewer.HelpBrowserWV import HelpWebPage currentUserAgentString = HelpWebPage().userAgent() xml = QXmlStreamReader(defaultUserAgents) while not xml.atEnd(): xml.readNext() if xml.isStartElement() and xml.name() == "separator": if menuStack: menuStack[-1].addSeparator() else: self.addSeparator() continue if xml.isStartElement() and xml.name() == "useragent": attributes = xml.attributes() title = attributes.value("description") userAgent = attributes.value("useragent") act = QAction(self) act.setText(title) act.setData(userAgent) act.setToolTip(userAgent) act.setCheckable(True) act.setChecked(userAgent == currentUserAgentString) act.triggered.connect(self.__changeUserAgent) if menuStack: menuStack[-1].addAction(act) else: self.addAction(act) self.__actionGroup.addAction(act) isChecked = isChecked or act.isChecked() if xml.isStartElement() and xml.name() == "useragentmenu": attributes = xml.attributes() title = attributes.value("title") if title == "v_a_r_i_o_u_s": title = self.tr("Various") menu = QMenu(self) menu.setTitle(title) self.addMenu(menu) menuStack.append(menu) if xml.isEndElement() and xml.name() == "useragentmenu": menuStack.pop() if xml.hasError(): E5MessageBox.critical( self, self.tr("Parsing default user agents"), self.tr( """<p>Error parsing default user agents.</p><p>{0}</p>""") .format(xml.errorString())) return isChecked
def loadState(self, dev, stateParam, stateID = ""): curExecContext = ScExecContext() curExecContext.stateMachine = self.stateMachine curHistoryState = None debug = True r = QXmlStreamReader(dev) while not r.atEnd(): r.readNext() if r.isStartElement(): logger.info("Element :<%s>", r.name()) # # <scxml> # name = r.name().lower() if name == "scxml": if stateID == "": topLevelState = curState = stateParam self.stateInfo[curState] = r.attributes().value("initial") if curState == self.stateMachine: pass # # <state> || <parallel> # elif name == "state" or name == "parallel": inRoot = False stateId = r.attributes().value("id") newState = None # # Create state # if curState is not None: logger.info("Creating state [%s] child of [%s]", stateId, curState.objectName()) type = QState.ExclusiveStates if name == "state" else QState.ParallelStates newState = QState(type, curState) # # ??? # elif stateId == stateID: topLevelState = newState = stateParam if newState is not None: self.stateInfo[newState] = r.attributes().value("initial") newState.setObjectName(stateId) # # initial state # if stateId is not "" and self.stateInfo[curState] == stateId: if curState == self.stateMachine: logger.info("Setting [%s] initial state to [%s]", self.stateMachine.objectName(), newState.objectName()) self.stateMachine.setInitialState(newState) else: logger.info("Setting [%s] initial state to [%s]", curState.objectName(), newState.objectName()) curState.setInitialState(newState) # # TODO implement src attribute management in state element # initialID = r.attributes().value("initial") self.stateByID[stateId] = newState curState = newState curExecContext.state = newState if debug: # Add entry and exit log curExecContext.script = 'logger.debug("[scxml] [debug] > Entering state: [' + stateId + ']")' curExecContext.type = ScExecContext.StateEntry curExecContext.applyScript() curExecContext.script = 'logger.debug("[scxml] [debug] < Exiting state: [' + stateId + ']")' curExecContext.type = ScExecContext.StateExit curExecContext.applyScript() # # <initial> # elif name == "initial": if curState is not None and self.stateInfo[curState] == "": logger.info("Creating state [%s] child of [%s]", stateId, curState.objectName()) newState = QState(curState) curState.setInitialState(newState) # # <history> # elif name == "history": if curState is not None: stateId = r.attributes().value("id") type = r.attributes().value("type") type = QHistoryState.ShallowHistory if type == "shallow" else QHistoryState.DeepHistory curHistoryState = QHistoryState(type) curHistoryState.setObjectName(stateId) self.stateByID[stateId] = curHistoryState # # <final> # elif name == "final": if curState is not None: stateId = r.attributes().value("id") f = QFinalState(curState) f.setObjectName(stateId) curExecContext.state = f self.statesWithFinal.add(curState) gp = curState.parentState() if gp is not None: if gp.childMode() == QState.ParallelStates: self.statesWithFinal.add() self.stateByID[stateId] = f if debug: # Add entry and exit log curExecContext.script = 'logger.debug("[scxml] [debug] > Entering final state: [' + stateId + ']")' curExecContext.type = ScExecContext.StateEntry curExecContext.applyScript() curExecContext.script = 'logger.debug("[scxml] [debug] < Exiting final state: [' + stateId + ']")' curExecContext.type = ScExecContext.StateExit curExecContext.applyScript() # # <script> # elif name == "script": txt = r.readElementText() # # The SCXML Processor MUST evaluate any <script> element that is a child # of <scxml> at document load time # if curExecContext.type == ScExecContext.Unknown and curState == topLevelState: # TODO execute script pass else: curExecContext.script += txt # # <log> # elif name == "log": curExecContext.script += 'logger.' + r.attributes().value("level") + '("[' + \ r.attributes().value("label") + '] [' + \ r.attributes().value("level") + '] ' + r.attributes().value("expr") + '")' # # <assign> # elif name == "assign": pass # # <if> # elif name == "if": pass # # <elseif> # elif name == "elseif": pass # # <else> # elif name == "else": pass # # <cancel> # elif name == "cancel": pass # # <onentry> # elif name == "onentry": curExecContext.type = ScExecContext.StateEntry curExecContext.script = "" # # <onexit> # elif name == "onexit": curExecContext.type = ScExecContext.StateExit curExecContext.script = "" # # <raise> # elif name == "raise": pass # # <send> # elif name == "send": pass # # <invoke> # elif name == "invoke": pass # # <transition> # elif name == "transition": if curHistoryState is not None: inf = ScHistoryInfo() inf.hstate = curHistoryState inf.defaultStateID = r.attributes().value("target") self.historyInfo.append(inf) else: inf = ScTransitionInfo() inf.targets = r.attributes().value("target").split() # TODO split targets curExecContext.type = ScExecContext.Transition curExecContext.script = "" if debug: curExecContext.script = 'logger.debug("[scxml] [debug] = Transitioning to: [' \ + ', '.join(inf.targets) + ']")' + '\n' curTransitions = list() inf.transitions = list() self.transitionsInf.append(inf) for pfx in r.attributes().value("event").split(' '): sigTransition = None if pfx == '': # For eventless transition create QScxmlEventlessTransition transition sigTransition = QScxmlEventlessTransition(self.stateMachine) elif pfx.startswith("q-signal:"): # For all q-signal event, add a QSxcmlSignalTransition self.signalEvents.append(pfx) # get object name (a.b.c) => a objName = pfx[pfx.index(':')+1:pfx.index('.')] # get object reference obj = self.stateMachine.registeredObjects[objName] # get signal reference for attr in pfx[pfx.index('.')+1:].split('.'): sig = getattr(obj, attr) obj = sig # create Signal transition sigTransition = QScxmlSignalTransition(sig, self.stateMachine) if sigTransition is not None: # add condition to transition sigTransition.setConditionExpression(r.attributes().value("cond")) # add transition to current state curState.addTransition(sigTransition) # append sigTransition to transition info inf.transitions.append(sigTransition) # append sigTransition to curTransitions list curTransitions.append(sigTransition) else: logger.error("Transition creation error") # # End element # elif r.isEndElement(): name = r.name().lower() # # </state> or </parallel> # if name == "state" or name == "parallel": if curState == topLevelState: return else: curState = curState.parent() curExecContext.state = curState # # </history> # elif name == "history": curHistoryState = None # # </final> # elif name == "final": curExecContext.state = curExecContext.state.parentState() # # </if> # elif name == "if": pass # # </send> </raise> # elif name == "send" or name == "raise": pass # # </onentry> </onexit> </scxml> # elif name == "onentry" or name == "onexit" or name == "scxml": curExecContext.state = curState curExecContext.type = ScExecContext.StateExit if name == "onexit" else ScExecContext.StateEntry curExecContext.applyScript() curExecContext.type = ScExecContext.Unknown curExecContext.script = "" # # </transition> # elif name == "transition": if curHistoryState is None: curExecContext.transitions = curTransitions curExecContext.type = ScExecContext.Transition curExecContext.applyScript() curExecContext.script = "" curExecContext.type = ScExecContext.Unknown