Well we have various ways to parse XML in Python but the best way to use is minidom() but before using minidom() you need to know how to use DOM(Document Object Model) which is the quickest and pretty straight forward:-
The xml.dom.minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller.
Below is the Python code that parses your XML code into Python:-
from xml.dom import minidom
xmldoc = minidom.parse('items.xml')
itemlist = xmldoc.getElementsByTagName('item') print(len(itemlist))
for s in itemlist:
If you do not want to use minidom() then you can use ElementTree which does not require DOM knowledge.
To use ElementTree firstly you will have to build an Element instance root from the XML by parsing a file by the following way:
import xml.etree.ElementTree as ET
root = ET.parse('thefile.xml').getroot()
The above code will parse the root from XML then you will use the below-mentioned code:-
for type_tag in root.findall('bar/type'):
value = type_tag.get('foobar')