parse xml file python code example

Example 1: python read xml

from xml.dom import minidom

# parse an xml file by name
mydoc = minidom.parse('items.xml')

items = mydoc.getElementsByTagName('item')

# one specific item attribute
print('Item #2 attribute:')
print(items[1].attributes['name'].value)

# all item attributes
print('\nAll attributes:')
for elem in items:
    print(elem.attributes['name'].value)

# one specific item's data
print('\nItem #2 data:')
print(items[1].firstChild.data)
print(items[1].childNodes[0].data)

# all items data
print('\nAll item data:')
for elem in items:
    print(elem.firstChild.data)

Example 2: how to open xml file element tree

import xml.etree.ElementTree as ET

tree = ET.parse('filename.xml') #this gets the file into a tree structure
tree_root = tree.getroot() #this gives us the root element of the file

Example 3: python string to xml

import xml.etree.ElementTree as ET

root = ET.fromstring(country_data_as_string)

Example 4: python parse xml string

root = ET.fromstring(xmlData)

Example 5: python elementtree load from string

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)