[英]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代码的解释,并将其分配给它们旁边的两个fruit(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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.