Python XML ElementTree - findall
Python XML ElementTree - findall
我正在处理 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)
我想要每个查询的标签和表达式。
例如,它将打印 me :
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'])
但我不知道如何同时为两者做。
任何评论都会有所帮助!
祝你有愉快的一天:)
您可以使用 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')
会得到所有 <query>
个元素,从根节点开始搜索
type_tag.findall('./where/condition')
将为您提供当前查询 tpye_tag
中的所有 <condition>
个元素
我正在处理 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)
我想要每个查询的标签和表达式。 例如,它将打印 me :
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'])
但我不知道如何同时为两者做。
任何评论都会有所帮助!
祝你有愉快的一天:)
您可以使用 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')
会得到所有<query>
个元素,从根节点开始搜索type_tag.findall('./where/condition')
将为您提供当前查询tpye_tag
中的所有
<condition>
个元素