[XML-SIG] an example of generating XML?

Martin v. Loewis martin@v.loewis.de
10 Sep 2002 08:36:44 +0200


"warren henning" <wkhenning@softhome.net> writes:

> Just show me the code to create something simple like:
> 
> <?xml version="1.0"?>
> <data>
>     <node id="1" ack="blah">This is a test node.</node>
>     <node id="2">So is this.</node>
> </data>

I recommend


print """<?xml version="1.0"?>
<data>
    <node id="1" ack="blah">This is a test node.</node>
    <node id="2">So is this.</node>
</data>
"""

If you meant to indicate that "bla" and "This is a test node." come
from some data structure, say,

class Node:
  def __init__(self, text, ack = None):
    self.text = text
    self.ack = ack
nodes = [Node("This is a test node.", "bla"), Node("So is this.")]

then I recommend to add a method to class Node

  def as_xml(self, id):
    if self.ack:
      ack = ' ack="%s"' % self.ack
    else:
      ack = ''
    return '<node id="%d"%s>%s</node>' % (id, ack, self.text)

print """<?xml version="1.0"?>
<data>
"""
for i in range(nodes)
  print nodes[i].as_xml(i)
print "</data>"

HTH,
Martin