#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import codecs
from xml.dom.minidom import getDOMImplementation
class Builder(object):
def __init__(self, root, impl=None):
if not impl:
impl = getDOMImplementation()
self.doc = impl.createDocument(None, root, None)
self.root = self.doc.documentElement
def add(self, parent, name, attrs=None, content=None):
e = self.doc.createElement(name)
if attrs:
for name, value in attrs.items():
e.setAttribute(name, value)
if content:
if isinstance(content, basestring):
content = self.doc.createTextNode(content)
e.appendChild(content)
if parent:
parent.appendChild(e)
return e
if __name__ == "__main__":
builder = Builder('table')
table = builder.root
table.setAttribute('class', 'matrix')
tr = builder.add(table, 'tr')
tr = builder.add(tr, 'td', None, 'cell')
f=open("sample.xml", 'w')
table.writexml(f)
f.close()
最終更新:2009年01月19日 17:17