UnboundLocalError when use element tree to parse XML in plugin QGIS
Question: I make plugin to open XML and read it then parse it to show some information,
this is code I use

    
    
    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)
    

I parse a big xml file (total 14 page when i print it) and one line that i
want to parse showed like this

    
    
    <gmd:denominator>
    <gco:Integer>ValueScale</gco:Integer>
    </gmd:denominator>
    

I want to put ValueScale to show in QlineEdit and i get error message say:

    
    
    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
    

can someone help me?


Answer: The problem lies probably here:

    
    
       for elem in doc.findall('{Default_Config/gco#}Integer'):
                a=elem.tag, elem.text
            print a
    
       self.ui.lineSkala.setText(a)
    

If `doc.findall` returns `None`, there will be no `a`. You need to check for
the presence of a:

    
    
    try:
        self.ui.lineSkala.setText(a)
    except (UnboundLocalError, NameError):
        do_here_something_else...
    

