Skip to content

Instantly share code, notes, and snippets.

@slogsdon7
Last active July 31, 2024 10:27
Show Gist options
  • Save slogsdon7/464810cf5855e37ab537d5932767dc62 to your computer and use it in GitHub Desktop.
Save slogsdon7/464810cf5855e37ab537d5932767dc62 to your computer and use it in GitHub Desktop.
xml parsing in python
from xml.etree import ElementTree
tree = ElementTree.parse('Users.xml')
root = tree.getroot() # <Element 'users' at 0x105f0e950>
#The root is an array/iterator, so child elements can be accessed with array syntax
row = root[0] # <Element 'row' at 0x105f0e9b0>
row.attrib['DisplayName'] # This is how you access attributes directly
data = []
for row in root:
user = {}
user['DisplayName'] = row.attrib['DisplayName'])
user['Location'] = row.attrib['Location']
data.append(user)
#You could also use a tuple instead of a dictionairy
for row in root:
data.append((row.attrib['DisplayName'], row.attrib['Location']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment