Alexander
Alexander

Reputation: 29

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>

I want to extract the Explanation of this XML code and assign it to both fruits(Type) next to them. This is my code:

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)

I am just getting the result for the first fruit of the tree structure.

Orange, this is a Citrus fruit.

But I would like to get all types with their explanation assigned next to it. Therefore the result should look like this:

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

Upvotes: 0

Views: 2258

Answers (1)

Cody Parker
Cody Parker

Reputation: 1121

You're looping through the Fruit element, not the types within. So, you would need to do something like this (there are other ways, too) to get those results:

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))

Upvotes: 1

Related Questions