i'm trying write xml piece of code
docs = xmlreportgenerator() docs.addmatchrow('fc barcelona','madryt','5:0') docs.save()
and wrote own method:
from lxml import etree class xmlreportgenerator: """""" root = etree.element('results') doc = etree.elementtree(root) #---------------------------------------------------------------------- def __init__(self): """""" def addmatchrow(self,teama,teamb, score): pageelement = etree.subelement(root,'flight',teama, teamb, score) """""" def save(self,path = none): outfile = open('matches.xml', 'w') doc.write(outfile)
nameerror: global name 'root' not defined process terminated exit code of 1 done
nameerror: global name 'doc' not defined process terminated exit code of 1 done
am missing something? i'm newbie in python (i have more experience in c#).
python explicit. instance variables must prepended self.
. class variables must prepended name of class.
here's fixed version. original subelement
call incorrect well:
from lxml import etree # derive 'object' if python 2.x (it default in python 3.x) class xmlreportgenerator(object): def __init__(self): # clearer init instance variables here. self.root = etree.element('results') self.doc = etree.elementtree(self.root) def addmatchrow(self,teama,teamb, score): # need self.root here pageelement = etree.subelement(self.root,'flight') # added data elements (or did want attributes?) etree.subelement(pageelement,'teama').text = teama etree.subelement(pageelement,'teamb').text = teamb etree.subelement(pageelement,'score').text = score def save(self,path = none): outfile = open('matches.xml', 'w') # need self.doc here self.doc.write(outfile) # code run if script executed directly, # skipped if script imported script. if __name__ == '__main__': docs = xmlreportgenerator() docs.addmatchrow('fc barcelona','madryt','5:0') docs.save()
Comments
Post a Comment