[Tutor] Retrieving the text of a XML tag with ElementTree

Kent Johnson kent37 at tds.net
Wed Sep 14 20:36:41 CEST 2005



Bernard Lebel wrote:
> Hello,
> 
> Let say I have this XML chunk:
> 
> 
> <?xml version="1.0"?>
> 
> <root>
>   <sceneobject name="Camera_Root" fullname="Camera_Root" type="CameraRoot">
>     <properties>
>       <property name="Visibility" fullname="Camera_Root.visibility"
> type="visibility">
>         <parameters>
>           <parameter scriptname="viewvis"
> fullname="Camera_Root.visibility.viewvis" type="Parameter"
> sourceclassname="nosource">False</parameter>
> 
> 
> I wish to retrieve the "False" between the opening/closing tags.
> I thought I could use something like:
> 
> 
> from elementtree.ElementTree import parse
> 
> oTree = parse( r'C:\temp\Camera_Root.xml' )
> 
> for oXMLObject in oTree.findall( '//sceneobject' ):
> 	if oXMLObject.attrib[ 'type' ] == 'CameraRoot':
> 		
> 		oXMLProps = oXMLObject.find( 'properties' )
> 		
> 		# We found the tag
> 		for oXMLProp in oXMLProps.findall( 'property' ):
> 			if oXMLProp.attrib[ 'name' ] == 'Visibility':
> 				print oXMLProp.text
> 
> 
> Now the print statements prints an empty line, wich is obviously not
> what I'm after :-)

You have to dig a little more, the text is part of the <parameter> element, not the <property> element. Something like
		for oXMLProp in oXMLProps.findall( 'property' ):
			if oXMLProp.attrib[ 'name' ] == 'Visibility':
				for param in oXMLProp.findall('.//parameter'):
					print param.text

I really wish ElementTree supported full XPath expressions. If it did this whole thing would almost be a one-liner - something like

for param in oTree.findall( '//sceneobject[@type="CameraRoot"]/properties/property[@name="Visibility"]/parameters/parameter'):
  print param.text

Sigh. XPath really rocks. Anyone want to port lxml to Windows?

Kent




More information about the Tutor mailing list