Element Tree Help

Reedick, Andrew jr9445 at ATT.COM
Mon Mar 24 12:20:09 EDT 2008


Robert Rawlins wrote:
> I have little to no experiance with element tree and I'm struggling to 
> find a way to parse the details from the XML document (attached) into 
> my application. Essentialy I'm looking to take the following document 
> and turn it into a dict of tuples, each dict element defines a 
> datasource with the key to the element being the 'name' which is 
> defined in the XML and then the value of the pair is a tuple which 
> contains the details of the datasource, like the host and port etc.


Here's another way to walk an ElementTree.  This one creates a hash of hashes which are normally more useful than tuples for property lookups.

import xml.etree.ElementTree as ET

tree = ET.ElementTree(file = "foo.xml")
d = {}
for ds in tree.findall("datasource"):

	name = ds.find('name').text
	d[name] = {}
	print 'datasource =', name

	for i in ds.findall('*'):
	#for i in ds.getiterator():  # also works

		if i.tag in ('datasource', 'name'):
			continue

		print '    ',i.tag, "=", i.text
		d[name][i.tag] = i.text

	print

print d

*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621





More information about the Python-list mailing list