我正在用python编写一个类以从XML解析数据,我想将XML文件名作为参数传递,以便可以在构造函数中初始化树和根。我该怎么做?到目前为止,这是我的代码:
import xml.etree.ElementTree as ET
class cParser:
def __init__(self, file):
tree = ET.parse(self.file)
root = tree.getroot()
def getFilename():
filename = root.attrib['filename']
print("Filename is: %s" %(filename))
c1 = cParser('pythonxml.xml')
c1.getFilename()
答案 0 :(得分:0)
尝试首先修正您的class
声明:
import xml.etree.ElementTree as ET
class cParser:
def __init__(self, file):
tree = ET.parse(file) # no need for self here
self.root = tree.getroot() # needs self here
def getFilename(self): # missed self in arg list
filename = self.root.attrib['filename'] # use self.root from init
print("Filename is: %s" % filename)
c1 = cParser('pythonxml.xml') # not a pythonic name for a class though
c1.getFilename() # and not a pythonic name for method