从 XML 文件 Python 获取数据

Get data from XML file Python

<Fruits>
    <Fruit>
        <Family>Citrus</Family>
        <Explanation>this is a Citrus fruit.</Explanation>
        <Type>Orange</Type>
        <Type>Lemon</Type>
    </Fruit>
</Fruits>

我想提取此 XML 代码的解释并将其分配给它们旁边的两个 fruits(Type)。这是我的代码:

import os
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")

for f in Fruit:
    Type = f.find("Type").text
    Explanation = f.find("Explanation").text

    print (Type, Explanation)

我刚刚得到树结构的第一个果实的结果。

Orange, this is a Citrus fruit.

但我想获得所有类型,并在其旁边分配解释。因此结果应该是这样的:

Orange, this is a Citrus fruit.
Lemon, this is a Citrus fruit.

您正在遍历 Fruit 元素,而不是其中的类型。所以,你需要做这样的事情(也有其他方法)来获得这些结果:

import os
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")

for f in Fruit:
    Explanation = f.find("Explanation").text
    Types = f.findall("Type")
    for t in Types:
        Type = t.text
        print ("{0}, {1}".format(Type, Explanation))