The XML file
Create a simple XML file, e.g. countries.xml
.
<?xml version="1.0"?> <data> <country name="Singapore"> <rank>4</rank> <year>2017</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>
Parsing XML file
This short tutorial uses xml.etree.ElementTree to parse through the XML file.
#!/usr/bin/python3 import xml.etree.ElementTree as ET tree = ET.parse('countries.xml') # Get the root element. root = tree.getroot() # Every element has a tag and an attribute. print("Tag name =", root.tag, "|", "Attribute = ", root.attrib) # Iterate over the children of an element, i.e. root. for child in root: print(child.tag, child.attrib) # You can directly access the child element using index. country=root[1] # <country name="Panama"> print(country.get('name')) year=root[1][1] # <year>2011</year> print(year.text) neighbor=root[1][3] # <neighbor name="Costa Rica" direction="W"/> print(neighbor.get('direction'))
Reference
- https://docs.python.org/3.7/library/xml.etree.elementtree.html