我制作插件来打开XML并读取它,然后解析它以显示一些信息,这是我使用的代码
from PyQt4 import QtCore, QtGui
from ui_latih import Ui_latih
import xml.etree.ElementTree as ETree
# create the dialog for zoom to point
class latihDialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
# Set up the user interface from Designer.
self.ui = Ui_latih()
self.ui.setupUi(self)
cariButton = self.ui.btnCari
QtCore.QObject.connect(cariButton, QtCore.SIGNAL('clicked()'),self.cari)
def cari(self, event=None):
#open dialog
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '*.xml')
self.ui.lineFile.setText(filename)
#panggil isi data
self.isiDataFile(filename)
def isiDataFile(self, nmfile):
#buka dengan open mode baca
teksFile = open(nmfile, 'r').read()
self.ui.textFile.setText(teksFile)
#parse XML FIle
self.parsethis(teksFile)
def parsethis(self, parse):
doc = ETree.fromstring(parse)
for elem in doc.findall('{Default_Config/gco#}Integer'):
a=elem.tag, elem.text
print a
self.ui.lineSkala.setText(a)
我解析了一个大的xml文件(打印时总共14页)和我要解析的一行显示如下
<gmd:denominator>
<gco:Integer>ValueScale</gco:Integer>
</gmd:denominator>
我想将ValueScale放在QlineEdit中显示,我收到错误信息:
File "C:\Users\Mr.Pakde/.qgis2/python/plugins\latih\latihdialog.py", line 65, in parsethis
self.ui.lineSkala.setText(a)
UnboundLocalError: local variable 'a' referenced before assignment
有人可以帮助我吗?
答案 0 :(得分:0)
问题可能在于:
for elem in doc.findall('{Default_Config/gco#}Integer'):
a=elem.tag, elem.text
print a
self.ui.lineSkala.setText(a)
如果doc.findall
返回None
,则不会a
。
您需要检查是否存在:
try:
self.ui.lineSkala.setText(a)
except (UnboundLocalError, NameError):
do_here_something_else...