0
<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.

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.