[英]How to use root.findall with AND condition
XML 是这样的:
<Section SectionLevel="1" SectionID="Food">
<Section SectionLevel="2" SectionID="Fruit">
<Content>Apple</Content>
</Section>
<Section SectionLevel="1" SectionID="Food">
<Section SectionLevel="2" SectionID="Meat">
<Content>Beef</Content>
</Section>
当级别 1 中的 SectionID = Food 和级别 2 中的 SectionID = Fruit 时,我想打印内容。 我找不到在 AND 条件下使用 XPath 的教程。
def main():
tree = ET.parse('data.xml')
root = tree.getroot()
for section in root.findall("./Section/[SectionID='Food']"):
and
for section in root.findall("./Section/Section/[SectionID='Fruit']"):
print(content)
在 xpath 中有and
,但我认为在这种情况下您不需要它。 我想你只需要把你的两个 xpath 放在一起......
.//Section[@SectionID='Food']/Section[@SectionID='Fruit']/Content
完整的例子...
import xml.etree.ElementTree as ET
from io import StringIO # using StringIO to simulate reading a file instead of a string
xml = """<doc>
<Section SectionLevel="1" SectionID="Food">
<Section SectionLevel="2" SectionID="Fruit">
<Content>Apple</Content>
</Section>
</Section>
<Section SectionLevel="1" SectionID="Food">
<Section SectionLevel="2" SectionID="Meat">
<Content>Beef</Content>
</Section>
</Section>
</doc>"""
doc = StringIO(xml)
tree = ET.parse(doc)
for content_elem in tree.findall(".//Section[@SectionID='Food']/Section[@SectionID='Fruit']/Content"):
print(content_elem.text)
印output...
Apple
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.