如何在 AND 条件下使用 root.findall
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)
打印输出...
Apple
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)
打印输出...
Apple