[XML-SIG] how to output xml from a python object

Martin v. Loewis martin@v.loewis.de
12 May 2002 16:49:47 +0200


"Dave Primmer" <primmer@hotmail.com> writes:

> I'd like to do something like take a simple python object and make an
> xml file. I've looked and looked but I can't find any docs on how to
> do this (only parsing). 

IMO, generating XML is much simpler than parsing it - you normally
don't need any library. Hence, there is no explicit library support
for it.

> If there is no xml.dom.builder anymore, how do i build a dom tree and
> then write it out with .toxml()?

If you absolutely think you need to create a DOM tree, you have to use
the normal DOM API for creation: use createDocument on the DOM
implementation, then use createElement on the document, and
appendChild to build the tree.

> I started out by just doing "<"+tag+">" stuff and writing elements for
> everthing but i'd like to be able to do xml attributes also.
> 
> i'd like to do:
> object.name = 'bob'
> object.city = 'sea'
> object.desc = '<p>blabedy blah. on and on</p>'
> to this:
> <object "name="bob" "city"="sea"><desc><p>blabedy blah. on and
> on</p></desc></object>

I recommend

print '<object name="%s" city="%s"><desc>%s</desc></object>' % \
   (object.name, object.city, object.desc)

Care is needed if the attributes may contain markup.

Regards,
Martin