我正在尝试提取XML文件中特定标签的内容.

样本XML:

crash

Crash

id

Crash Instance

INT

key

accident_key

Case Identifier

string

CHAR(9)

accident_year

Crash Year

dim

INT

vehicle

Vehicle

id

Vehicle Instance

INT

crash_id

Crash Instance

INT

我想从节点中提取标记的所有内容,但仅限于崩溃事实.

到目前为止,这是我的代码.

def header(filename, fact):

lst = []

tree = ET.parse(filename) #read in the XML

for fact in tree.iter(tag = 'fact'):

factname = fact.find('name').text

if factname == fact: #choose the fact to pull from

for var in fact.iter(tag = 'variable'):

name = var.find('name').text

lst.append(name)

return lst #return a list of all the tags from the Crash fact

newlst = header('schema.xml','crash')

我的输出newlst应该是Crash事实中所有标记的列表.但是它总是返回空的.

奇怪的是,如果我对所有内容进行硬编码(并删除该函数),它将返回正确的输出:

lst = []

tree = ET.parse('schema.xml')

for fact in tree.iter(tag = 'fact'):

factname = fact.find('name').text

if factname == 'crash':

for var in fact.iter(tag = 'variable'):

name = var.find('name').text

lst.append(name)

print(lst)

Output: ['id',

'accident_key',

'accident_year']

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐