从XML文件Python获取数据

时间:2016-05-20 22:16:13

标签: python xml extraction

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

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

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.

1 个答案:

答案 0 :(得分:1)

您正在遍历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))