extra xml header with ElementTree?

Tim Arnold tiarno at sas.com
Fri May 25 12:03:54 EDT 2007


"Gerard Flanagan" <grflanagan at yahoo.co.uk> wrote in message 
news:1180107283.591686.48190 at u30g2000hsc.googlegroups.com...
> On May 25, 3:55 pm, "Tim Arnold" <tia... at sas.com> wrote:
>> Hi, I'm using ElementTree which is wonderful. I have a need now to write 
>> out
>> an XML file with these two headers:
>> <?xml version="1.0" encoding="UTF-8" ?>
>> <?NLS TYPE="org.eclipse.help.toc"?>
>>
>> My elements have the root named tocbody and I'm using:
>> newtree = ET.ElementTree(tocbody)
>> newtree.write(fname)
>>
>> I assume if I add the encoding arg I'll get the xml header:
>> newtree = ET.ElementTree(tocbody)
>> newtree.write(fname,encoding='utf-8')
>>
>> but how can I get the <?NLS TYPE="org.eclipse.help.toc"?> into the tree?
>>
>> python2.4.1,hpux10,ElementTree1.2.6
>>
>
> #This import is for 2.5, change for 2.4
> from xml.etree import cElementTree as ET
>
> tocbody = '<toc><item>one</item><item>two</item></toc>'
>
> doc = ET.ElementTree(ET.fromstring(tocbody))
>
> outfile = open('\\working\\tmp\\toctest.xml', 'w')
>
> outfile.write('<?xml version="1.0" encoding="UTF-8" ?>')
>
> outfile.write('<?NLS TYPE="org.eclipse.help.toc"?>')
>
> doc._write(outfile, doc._root, 'utf-8', {})
>
> outfile.close()
>
> -----------------
>
>  <?xml version="1.0" encoding="UTF-8" ?>
>  <?NLS TYPE="org.eclipse.help.toc"?>
>  <toc>
>  <item>one</item>
>  <item>two</item>
>  </toc>
>

thanks, this works well. After looking at the ET code, I just used the 
'write' method straight since it calls _write in turn.

thanks again,
--Tim





More information about the Python-list mailing list