DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Using ElementTree

03.17.2006
| 8859 views |
  • submit to reddit
        <a href=http://effbot.org/zone/element-index.htm>ElementTree</a> is a library that make XML processing in python
much, much easier. It will be included in Python 2.5 too.
Here's how to use it to read/extract XML
from elementtree.ElementTree import parse
tree = parse(filename)
doc = tree.getroot()

# Element type (name): 
print doc.tag
# Element text: 
print doc.text
# get the child of element type book
book = doc.find('book')

# element's attribute
book.keys()
book.items()
book.get('COLOR')

# first matching element's text
booktext = doc.findtext('book')
Read more <a href=http://reagle.org/joseph/blog/technology/python/elementtree-model>here</a> and <a href=http://www.amk.ca/talks/2006-02-07/>here</a>.