我正在处理XML文件。我的档案是这样的:
import xml.etree.ElementTree as ET
xml = '''
<root>
<query label="nom1" code="1234">
<where a="1" b="2">
<condition id="1534" expr="expression1"/>
</where>
</query>
<query label="nom2" code="2345">
<where a="2" b="3">
<condition id="6784" expr="expression2"/>
</where>
</query>
</root>
'''
myroot = ET.fromstring(xml)我想要每个查询的标签和费用。例如,它将打印我:
query 1 :
nom1
expression1
query 2:
nom2
expression2你知道我该怎么做吗?我知道如何打印所有标签:
for type_tag in myroot.findall('root/query'):
print(type_tag.attrib['label'])以及如何打印所有的费用:
for e in myroot.findall("root/query/.//*[@expr]"):
print(e.attrib['expr'])但我不知道如何在同一时间做这两件事。
任何评论都是有帮助的!
祝你今天愉快:)
发布于 2020-04-01 14:22:22
可以使用findall()相对于相应的元素进行搜索:
for i, type_tag in enumerate(myroot.findall('./query')):
print(f'query {i+1}:')
print(type_tag.attrib['label'])
for e in type_tag.findall('./where/condition'):
print(e.attrib['expr'])
# query 1:
# nom1
# expression1
# query 2:
# nom2
# expression2解释:
myroot.findall('./query')将使您从根nodetype_tag.findall('./where/condition')开始搜索所有的<query>元素,从而获得当前查询tpye_tag中的所有<condition>元素。
https://stackoverflow.com/questions/60972613
复制相似问题