简体   繁体   中英

Parse XML with ElementTree

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM