[XML-SIG] ANN: XMLBuilder 1.0

Mike Hostetler hostetlerm at gmail.com
Wed Aug 25 20:54:28 CEST 2004


I read a good blog entry about a Builder object in Ruby [1] and I
thought Python needed one.

Introducing XMLBuilder.  It's nothing special, but it works quite
well.  You create an XMLBuilder object, send it some dictionary data,
and it will generate the XML for you.  My version also allows nesting
another XMLBuilder object inside, as well as adding them together
(though that may not work like you want it to).

It's easier to show than to describe.  Here are some examples:

>>> from xmlbuilder import XMLBuilder
>>> b2 = XMLBuilder()
>>> b2.name = {"last":"flintstone", 'attr':{"type":"friend"}, "first":"fred"}
>>> print b2
<?xml version="1.0" ?>
<name type="friend"><last>flintstone</last><first>fred</first></name>
>>> b1.contacts = {"owner":"thehaas at binary.net",
...     "contact":b2}
>>> print b1
<?xml version="1.0" ?>
<contacts><owner>thehaas at binary.net</owner><contact><name type="friend"><last>f\
lintstone</last><first>fred</first></name></contact></contacts>
>>> b = b1+b2
>>> print b
<?xml version="1.0" ?>
<contacts><contacts><owner>thehaas at binary.net</owner><contact><name type="frien\
d"><last>flintstone</last><first>fred</first></name></contact></contacts><name \
type="friend"><last>flintstone</last><first>fred</first></name></contacts>

Note that "attr" isn't required to start an attribute dictionary --
any dictionary value inside a dictionary will trigger it.

The good news -- it only used Python 2.3.  The internal XML rendering
is done with minidom.  Py23 is required because it uses importNode
when an object is nested.

Grab it at:
http://users.binary.net/thehaas/lab/files/xmlbuilder.py

[1]http://onestepback.org/index.cgi/Tech/Ruby/BuilderObjects.rdoc
-- 
Mike Hostetler
thehaas at binary.net
http://www.binary.net/thehaas


More information about the XML-SIG mailing list