Search code examples
pythonxmltags

python get xml tag list


i have this xml file :

<root>
    <discovers>
        <discover>
            <zoulou>zag</zoulou>
            <yotta>bob</yotta>
            <alpha>ned</alpha>
        </discover>

        <discover>
            <beta>Zorro</beta>
            <omega>Danseur</omega>
        </discover>
    </discovers>
</root>

in python3.6 i want to get this output :

[[zoulou,yotta,alpha],[beta,omega]]

actually i can have all tag with this code in python

tree = etree.parse("./file.xml")
[elt.tag for elt in tree.findall("discovers/discover/*")]

i have this output :

['zoulou', 'yotta', 'alpha', 'beta', 'omega']

i don't found function for separate tag list by parent node, can you help me ? i don't know how to separate my discover node


Solution

  • This can be accomplished by nesting list comprehensions. One option is to find all 'discover'-elements in the outer comprehension and then find any child elements.

    [[ch.tag for ch in elt.findall('*')] for elt in doc.findall("discovers/discover")]
    
    [['zoulou', 'yotta', 'alpha'], ['beta', 'omega']]