Skip to content

Instantly share code, notes, and snippets.

@dsaiztc
Last active August 29, 2015 14:23
Show Gist options
  • Save dsaiztc/6c03f7c30f14d45a6501 to your computer and use it in GitHub Desktop.
Save dsaiztc/6c03f7c30f14d45a6501 to your computer and use it in GitHub Desktop.
import xml.etree.cElementTree as ET
# Pyhton implementation: import xml.etree.ElementTree as ET
filename = 'myfile.xml'
tag = ''
text = ''
attrs = {}
# Document Tree XML parser (load the entire document into memory)
tree = ET.parse(filemane)
root = tree.getroot()
root = ET.fromstring(data_as_string) # Reading the data from a string
# Iterate over childs of an element
for child in root:
pass
# iterate recursively over all the sub-tree
for tag in root.iter():
pass
# Interate over all tags with 'tag-name'
for tag in root.iter('tag-name'):
pass
# Event-driven XML parser (we can specify what events we want to capture: start tag, end tag)
for event, elem in ET.iterparse(filename):
tag = elem.tag
text = elem.text
attrs = elem.attrib
elem.find('tag-name') # first match with 'tag-name'
for elm in elem.findall('tag-name'): # all matches with 'tag-name'
pass
# XPath support
for elm in elem.findall('./subtag/subtag/tag-name'):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment