Get all xml attribute values ​​in python3 using ElementTree

I have the following xml file

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

      

I want to write python 3 code using ElementTree to get the names of all countries. Thus, the end result must be dict

either array

of

['Liechtenstein', 'Singapore', 'Panama']

I am trying to do this with Xpath but I am not getting anything. So my code looks like this

import xml.etree.ElementTree as ET
tree = ET.parse(xmlfile)
root = tree.getroot()

names = root.findall("./country/@name")

      

However the above does not work as I feel like my xpath is wrong.

+3


source to share


2 answers


Use findall()

to get all tags country

and get attribute name

from .attrib

dictionary:

import xml.etree.ElementTree as ET

data = """your xml here"""

tree = ET.fromstring(data) 
print([el.attrib.get('name') for el in tree.findall('.//country')])

      

Printing ['Liechtenstein', 'Singapore', 'Panama']

.

Note that you cannot get attribute values ​​using xpath expression //country/@name

as xml.etree.ElementTree

it only provides limited support for Xpath .




FYI, lxml

provides more complete support for xpath and therefore makes it easier to get attribute values:

from lxml import etree as ET

data = """your xml here"""

tree = ET.fromstring(data)
print(tree.xpath('//country/@name'))

      

Printing ['Liechtenstein', 'Singapore', 'Panama']

.

+3


source


you can use

 import xml.etree.ElementTree as ET

 xml=ET.fromstring(contents)



xml.find('./element').attrib['key']

      



Highlight source here

0


source







All Articles