How to generate XML

Dave Kuhlman dkuhlman at
Wed Feb 13 11:37:51 EST 2002

Irmen de Jong <usenet at> wrote:
> "Martin von Loewis" <loewis at> wrote in message
> news:j44rmko5s6.fsf at
>> I'm amazed that people always start proposing difficult-to-use
>> libraries when this question comes up. I'd prefer to use
>> print "<foo/>"

For the special case where you have a tree structure whose nodes
are instances of Python classes, implement an "export" method in
each class something like the following:

    def export(self, outfile, level):
        showIndent(outfile, level)
        for element in self.subelements:
            element.export(outfile, level + 1)
        showIndent(outfile, level)

where showIndent is, perhaps, as follows:

    def showIndent(outfile, level):
        for idx in range(level):
            outfile.write('    ')

Then call export(outfile, 0) on the root node of the tree.

I have had this special case/need quite often.  Following the above
conventions makes it quite ease to generate an XML representation
of my data structures.

  - Dave

Dave Kuhlman
dkuhlman at

-----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----

More information about the Python-list mailing list