1

I'm trying to parse a xml with the below content

<File version="5.6">
<Parent name="A">
<Child name="a"/>
<Child name="b"/>
</Parent>

<Parent name="B">
<Child name="c"/>
<Child name="d"/>
</Parent>

<Parent name="C">
<Child name="e"/>
<Child name="f"/>
</Parent>

</File>

And I used the following code

for child in tree.getroot().findall('./Parent/Child')
     print child.attrib.get("name")

It just print all the name of children without the parent names. Can I print the relevant parent name of each child like this?

A has a b
B has c d
C has e f

1 Answer 1

2

Iterate over parents, then find children of the parents.

for parent in tree.findall('./Parent'):
    children = [child for child in parent.findall('./Child')]
    print '{} has {}'.format(parent.get('name'), ' '.join(c.get('name') for c in children))

Response to the comment

Using lxml, you can access parent node with getparent() method.

import lxml.etree
tree = lxml.etree.parse('1.xml')
for child in tree.findall('./Parent/Child'):
    print '{} has {}'.format(child.getparent().get('name'), child.get('name'))
Sign up to request clarification or add additional context in comments.

2 Comments

Can I iterate all the children and find their parent instead?
@JohnnyChen, You can, if you use lxml instead of xml.etree.ElementTree.

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.