[XML-SIG] Learning to use elementtree

J. Cliff Dyer jcd at unc.edu
Wed Apr 2 21:36:09 CEST 2008


On Wed, 2008-04-02 at 15:28 -0400, Doran, Harold wrote:
> Indeed, navigating the xml is tough (for me). I have been able to get
> the following to work. I put in "Sub Element" to indicate the new
> section of data. But, from looking at the text output, one doesn't know
> which item these sub elements belong to. I think the solution is to
> create an index like 13965-0 to show that this is the subinformation
> from the item above it. That seems to be where I am getting stuck.
> Although, I am open to other suggestions on how to best represent the
> output.
> 
> from xml.etree.ElementTree import ElementTree as ET
> 
> filename = raw_input("Please enter the AM XML file: ")
> new_file = raw_input("Save this file as: ")
> 
> # create a new file defined by the user
> f = open(new_file, 'w')
> 
> et = ET(file=filename)
> 
> for statentityref in \
> et.findall('admin/responseanalyses/analysis/analysisdata/statentityref')
> :
>     for statval in statentityref.findall('statval'):
>       print >> f, statentityref.attrib['id'], '\t',
> statval.attrib['type'], '\t', statval.attrib['value']
> 
> f.write("\n\n")
> f.write("Sub Element\n\n")
> 
> for statentityref in \
> et.findall('admin/responseanalyses/analysis/analysisdata/statentityref/s
> tatentityref'):
>     for statval in statentityref.findall('statval'):
>       print >> f, statentityref.attrib['id'], '\t',
> statval.attrib['type'], '\t', statval.attrib['value']
> f.close() 

Do you want your second statentityref loop to be based on its parent
statentityref?  If so, you need to nest it in the original loop, and use
an xpath relative to your outer statentityref (and watch for name
collisions).





More information about the XML-SIG mailing list