我正在尝试使用Python3.x解析XML文件。如果找到标签,我想返回True,否则返回False。我试图一次读取一行并检查 - 如果找不到则使用递归,但我不确定实现这一目标的最有效方法是什么。实现这一目标的最有效方法是什么? 这是我的代码:
class XmlFinder():
def __init__(self, filename):
self._filename = filename
self._tokens = []
def find(self, tag):
''' Accepts tag to search for - Parse the file, return True if tag is found and False if not. '''
self._tag = tag
with open(self._filename, 'rt') as f:
for line in f:
line = line.strip()
tokens = line.split()
if self._tag == self._tokens:
return True
else:
return False
XmlFinder.find(self, self._tag)
def main():
x = XmlFinder("filename")
tag = '<to/>'
x.find(tag)
main()
我以前从未解析过XML文件,所以这对我来说是全新的。
答案 0 :(得分:0)
考虑使用像BeautifulSoup
这样的库from BeautifulSoup import BeautifulStoneSoup
class XmlFinder():
def __init__(self, filename):
self._filename = filename
with file(filename, "r") as file_h:
self.soup = BeautifulStoneSoup(file_h.read())
def find(self, tag):
return True if self.soup.find(tag) else False
def main():
x = XmlFinder("filename")
tag = 'to'
x.find(tag)
main()