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())] = string_(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 load(self, fname=None): __fname = fname or self.__fname assert isinstance(__fname, str), '' if not os.path.exists(__fname): self.__error = 'File not exists' self.__error_flag = True return None try: xmlFile = QFile(__fname) root = None if xmlFile.open(QIODevice.ReadOnly): try: reader = QXmlStreamReader(xmlFile) root = self.__loadNodesViaStream(reader) if reader.hasError(): self.__error = reader.errorString() self.__error_flag = True except Exception as e: self.__error = str(e) self.__error_flag = True finally: xmlFile.close() return root except Exception as e: self.__error = str(e) self.__error_flag = True return None
def __init__(self, mapReader): self.p = mapReader self.mMap = None self.mError = QString('') self.mReadingExternalTileset = False self.xml = QXmlStreamReader() self.mGidMapper = GidMapper()
def readObjectTypes(self, fileName): self.mError = '' objectTypes = QVector() file = QFile(fileName) if (not file.open(QIODevice.ReadOnly | QIODevice.Text)): self.mError = QCoreApplication.translate("ObjectTypes", "Could not open file.") return objectTypes reader = QXmlStreamReader(file) if (not reader.readNextStartElement() or reader.name() != "objecttypes"): self.mError = QCoreApplication.translate( "ObjectTypes", "File doesn't contain object types.") return objectTypes while (reader.readNextStartElement()): if (reader.name() == "objecttype"): atts = reader.attributes() name = QString(atts.value("name")) color = QColor(atts.value("color")) objectTypes.append(ObjectType(name, color)) reader.skipCurrentElement() if (reader.hasError()): self.mError = QCoreApplication.translate( "ObjectTypes", "%s\n\nLine %d, column %d" % (reader.errorString(), reader.lineNumber(), reader.columnNumber())) return objectTypes return objectTypes
def loadNodes2(fname): '''Load nodes with XML StreamReader''' def loadNodesViaStream(reader): assert isinstance(reader, QXmlStreamReader) _item = None while not reader.atEnd(): reader.readNext() if reader.isStartElement(): if reader.name() == 'item': attributes = reader.attributes() tag_name = attributes.value('tag_name') print('tag name: {}'.format(tag_name)) item = TagTreeItem(tag_name) if _item is not None: _item.appendChild(item) _item = item elif reader.isEndElement(): parent = _item.parent() if parent is not None: _item = parent return _item if not os.path.exists(fname): print('File not exists') return None xmlFile = QFile(fname) if xmlFile.open(QIODevice.ReadOnly): reader = QXmlStreamReader(xmlFile) root = loadNodesViaStream(reader) if reader.hasError(): return root return root
def _handle_reply(self, reply, request, handler, xml, refresh): error = int(reply.error()) if error: log.error("Network request error for %s: %s (QT code %d, HTTP code %s)", reply.request().url().toString(QUrl.RemoveUserInfo), reply.errorString(), error, repr(reply.attribute(QtNetwork.QNetworkRequest.HttpStatusCodeAttribute)) ) if handler is not None: handler(reply.readAll(), reply, error) else: redirect = reply.attribute(QtNetwork.QNetworkRequest.RedirectionTargetAttribute) fromCache = reply.attribute(QtNetwork.QNetworkRequest.SourceIsFromCacheAttribute) cached = ' (CACHED)' if fromCache else '' log.debug("Received reply for %s: HTTP %d (%s) %s", reply.request().url().toString(QUrl.RemoveUserInfo), reply.attribute(QtNetwork.QNetworkRequest.HttpStatusCodeAttribute), reply.attribute(QtNetwork.QNetworkRequest.HttpReasonPhraseAttribute), cached ) if handler is not None: # Redirect if found and not infinite if redirect: url = request.url() # merge with base url (to cover the possibility of the URL being relative) redirect = url.resolved(redirect) if not XmlWebService.urls_equivalent(redirect, reply.request().url()): log.debug("Redirect to %s requested", redirect.toString(QUrl.RemoveUserInfo)) redirect_host = string_(redirect.host()) redirect_port = self.url_port(redirect) redirect_query = dict(QUrlQuery(redirect).queryItems(QUrl.FullyEncoded)) redirect_path = redirect.path() original_host = string_(url.host()) original_port = self.url_port(url) if ((original_host, original_port) in REQUEST_DELAY and (redirect_host, redirect_port) not in REQUEST_DELAY): log.debug("Setting rate limit for %s:%i to %i" % (redirect_host, redirect_port, REQUEST_DELAY[(original_host, original_port)])) REQUEST_DELAY[(redirect_host, redirect_port)] =\ REQUEST_DELAY[(original_host, original_port)] self.get(redirect_host, redirect_port, redirect_path, handler, xml, priority=True, important=True, refresh=refresh, queryargs=redirect_query, cacheloadcontrol=request.attribute(QtNetwork.QNetworkRequest.CacheLoadControlAttribute)) else: log.error("Redirect loop: %s", reply.request().url().toString(QUrl.RemoveUserInfo) ) handler(reply.readAll(), reply, error) elif xml: document = _read_xml(QXmlStreamReader(reply)) handler(document, reply, error) else: handler(reply.readAll(), reply, error)
def __feedLoaded(self, reply): """ Private slot to extract the loaded feed data. @param reply reference to the network reply @type QNetworkReply """ 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 parse_document(self, xml_document): self._xml_parser = QXmlStreamReader(xml_document) # xml_parser.setDevice(xml_document) data = self.parser_loop() if self._xml_parser.hasError(): raise NameError(self._xml_parser.errorString()) # self._xml_parser.clear() self._xml_parser = None return data
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 updateUiSvg(self,color_list): svgXmlStreamReader = QXmlStreamReader('<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n' + self.svgBoxArraySrc(10,10,40,5,24,4,color_list) + '</svg>\n') svgRender = QSvgRenderer() svgRender.load(svgXmlStreamReader) svgPixmap = QPixmap(480,80) svgPixmap.fill(QtCore.Qt.transparent) svgPainter = QPainter(svgPixmap) svgRender.render(svgPainter) self.ui.label_8.setPixmap(svgPixmap) self.ui.label_8.setAlignment(QtCore.Qt.AlignCenter) svgPainter.end()
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