Python / XML:TypeError:“列表”对象不可调用

时间:2019-10-02 18:01:01

标签: python xml lxml

我有一些需要应用并存储到变量中的元素列表。由于某种原因,它不接受列表中的元素?

import glob
import xmltodict
import lxml.etree as etree

xml_files = glob.glob('dir/*.xml')

list_of_xml = []
for l in [etree.parse(x) for x in xml_files]:
    list_of_xml.append(l)
print(list_of_xml)

# printOutput
[<lxml.etree._ElementTree at 0x17406866b88>,
 <lxml.etree._ElementTree at 0x17406795cc8>,
 <lxml.etree._ElementTree at 0x174068ed7c8>]

for e in list_of_xml():
    store_into_a_variable = xmltodict.parse(etree.tostring(e))


# error: TypeError: 'list' object is not callable

为什么会出现此错误?我已经多次将其用于循环类型的功能/表示法以获得一定的输出。

1 个答案:

答案 0 :(得分:1)

您不会像函数那样调用列表:

for e in list_of_xml():应该是for e in list_of_xml:

您的整个代码段应为:

import glob
import xmltodict
import lxml.etree as etree

xml_files = glob.glob('dir/*.xml')

list_of_xml = []
for l in [etree.parse(x) for x in xml_files]:
    list_of_xml.append(l)
print(list_of_xml)

# printOutput
[<lxml.etree._ElementTree at 0x17406866b88>,
 <lxml.etree._ElementTree at 0x17406795cc8>,
 <lxml.etree._ElementTree at 0x174068ed7c8>]

for e in list_of_xml:
    store_into_a_variable = xmltodict.parse(etree.tostring(e))