[XML-SIG] how to output xml from a python object
paul@boddie.net
paul@boddie.net
13 May 2002 10:22:00 -0000
>"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).
martin@v.loewis.de (Martin v. Loewis) wrote:
>
>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.
I recommend avoiding these printing exercises, for mainly the same reasons that
people should avoid quoting values in SQL statements - it's easy to forget to
quote things, and while security holes are less likely to be opened in this
case, getting some valid input and then seeing things go badly wrong is not
very appealing.
By the time quoting functions and other extra safeguards are included in your
code, you would have been better off in terms of code readability,
standardisation and extensibility if you had just used the DOM instead. After
all, the various serialisation functions and classes in PyXML have been
designed to do this kind of thing, and I don't believe in reinventing the wheel
poorly.
On a related note, I uploaded my introductory document again, and this is
precisely the kind of thing I covered in that document:
http://www.boddie.org.uk/python/XML_intro.html
Having had to maintain code which did lots of print statements (in Perl as
well, for increased maintenance excitement), I can see lots of benefits in not
using that approach. Another benefit of the DOM, of course, is the random-
access nature of the technology - as soon as you decide you need to revisit
parts of your generated document in your program in order to add "extra stuff"
(and I'm not saying you definitely will, but it's not unheard of), you'll
probably end up doing a big rewrite of the program to use the DOM anyway.
Paul