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']
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+"/*")})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With