A Simple Python Elementtree Example

I just which folks would include simple examples of stuff like XML parsing with ElementTree in Python. Here is mine.

# http://www.amk.ca/talks/2006-02-07/
# http://docs.python.org/lib/elementtree-functions.html
# http://effbot.org/zone/element.htm#searching-for-subelements
import xml.etree.ElementTree as ET
input = '''


001
Chuck


009
Brent



'''
stuff = ET.fromstring(input)
lst = stuff.findall("users/user")
print len(lst)
for item in lst:
print item.attrib["x"]
item = lst[0]
ET.dump(item)
item.get("x")   # get works on attributes
item.find("id").text
item.find("id").tag
for user in stuff.getiterator('user') :
print "User" , user.attrib["x"]
ET.dump(user)

Comments are closed.