Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch all the child nodes of an XML using python?

This is my XML file

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

like image 331
radh Avatar asked Jun 06 '17 14:06

radh


2 Answers

Use ElementTree lib to pull out the child nodes. This might help you.

import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
for child in root:
  print({x.tag for x in root.findall(child.tag+"/*")})
like image 55
voidpro Avatar answered Sep 19 '22 17:09

voidpro


The solution using xml.etree.ElementTree module:

import xml.etree.ElementTree as ET

tree = ET.parse("yourxml.xml")
root = tree.getroot()
tag_names = {t.tag for t in root.findall('.//country/*')}

print(tag_names)  # print a set of unique tag names

The output:

{'gdp', 'rank', 'neighbor', 'year'}

  • './/country/*' - xpath expression to extract all child elements of node country
like image 33
RomanPerekhrest Avatar answered Sep 18 '22 17:09

RomanPerekhrest