【问题标题】:How do I pass an XML file as a parameter in a python method?如何在 python 方法中将 XML 文件作为参数传递?
【发布时间】:2019-02-11 14:52:50
【问题描述】:

我正在用 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()

【问题讨论】:

  • 您似乎已经将文件名传递给cParser。这个问题不清楚。
  • ... 而且您的缩进也是错误的。你能改正吗?

标签: python xml parsing elementtree


【解决方案1】:

首先尝试修复您的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

【讨论】:

  • 对我来说是正确的,这里复制我的代码时一定有问题
  • 那么现在有什么问题?
  • 当我尝试运行代码时出现 AttributeError: file cParser has no file attribute
  • 正如我所说,你的类声明是错误的。使用我的回答中的类声明。
  • 谢谢你成功了!我还在学习 python,所以如果我的代码读起来很痛苦,我深表歉意......
猜你喜欢
  • 2010-10-16
  • 2017-07-29
  • 1970-01-01
  • 2014-03-23
  • 2017-10-12
  • 2011-10-14
  • 2020-04-01
相关资源
最近更新 更多