Monday, January 24, 2005

testing ElementTree

Testing cElementTree...

from SimpleXMLTreeBuilder import *
import cElementTree as ElementTree

def xml2elem(xmlData):
p=TreeBuilder()
p.feed(xmlData)
return p.close()

if __name__ == "__main__":
text = """ root content
tag 1 text
content of tag2
deeper
tag2 tail

"""
elem=xml2elem(text)
print 'elem.Tag->', elem.tag # elem root
print 'findall->', elem.findall('tag1')[0].text # tag1 text
print 'interrogate second child...'
print ' ', elem.getchildren()[1].tag # tag2
print ' ', elem.getchildren()[1].items() # [('id', '2'), ('att2', 'val2')]
print ' ', elem.getchildren()[1].getchildren()[0].tag # next level gets... deeper
print 'for child -> elems children but not grandchildren'
for child in elem:
print ' ', child.tag #tag1 tag2 (but not deeper)

file=open('text.xml','w'); file.write('text'); file.close

print 'for elem in iterparse -> all levels...'
for event, elem in ElementTree.iterparse('test.xml'):
print ' ', elem.tag # #tag1 tag2 AND deeper


elem.Tag-> root
findall-> tag 1 text
interrogate second child...
tag2
[('id', '2'), ('att2', 'val2')]
deeper
for child -> elems children but not grandchildren
tag1
tag2
for elem in iterparse -> all levels...
tag
deeper
tag2
root