Home > Mobile >  XML loop by specific parent element to find children
XML loop by specific parent element to find children

Time:03-20

I want to loop and group by 'country' and access the child elements

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

I tried below and didn't work for me. please advice

parser = ElementTree.XMLParser()
tree = ElementTree.fromstring(read_file, parser)
for elem in tree.findall('.//country'):
    print((elem.tag, elem.text))

CodePudding user response:

works for me

import xml.etree.ElementTree as ET

xt =("""<?xml version="1.0"? xmlns="foobar">
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>""")



ns = "{foobar}"

r = ET.fromstring(xt)
for x in r.findall(f".//{ns}country"):
    print(f"{x.tag}:{x.attrib['name']}")
    for y in x.findall('.//'):
        print(f" {y.tag}:{y.text}")
  • Related